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
[Feat] Add /image/edits on LiteLLM (#11123)
Ishaan Jaff702b5fec22e4
diff --git a/litellm/images/main.py b/litellm/images/main.pyindex 09db4aef20b..8270879ba8d 100644--- a/litellm/images/main.py+++ b/litellm/images/main.py@@ -584,7 +584,7 @@ def image_edit(try:litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignorelitellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None)- _is_async = kwargs.pop("adelete_responses", False) is True+ _is_async = kwargs.pop("async_call", False) is True# get llm provider logiclitellm_params = GenericLiteLLMParams(**kwargs)diff --git a/litellm/images/utils.py b/litellm/images/utils.pyindex 4bf338605a2..7b1875c4932 100644--- a/litellm/images/utils.py+++ b/litellm/images/utils.py@@ -1,7 +1,10 @@+from io import BufferedReader, BytesIOfrom typing import Any, Dict, cast, get_type_hintsimport litellm+from litellm.litellm_core_utils.token_counter import get_image_typefrom litellm.llms.base_llm.image_edit.transformation import BaseImageEditConfig+from litellm.types.files import FILE_MIME_TYPES, FileTypefrom litellm.types.images.main import ImageEditOptionalRequestParams@@ -69,3 +72,71 @@ class ImageEditRequestUtils:}return cast(ImageEditOptionalRequestParams, filtered_params)++ @staticmethod+ def get_image_content_type(image_data: Any) -> str:+ """+ Detect the content type of image data using existing LiteLLM utils.++ Args:+ image_data: Can be BytesIO, bytes, BufferedReader, or other file-like objects++ Returns:+ The MIME type string (e.g., "image/png", "image/jpeg")+ """+ try:+ # Extract bytes for content type detection+ if isinstance(image_data, BytesIO):+ # Save current position+ current_pos = image_data.tell()+ image_data.seek(0)+ bytes_data = image_data.read(+ 100+ ) # First 100 bytes are enough for detection+ # Restore position+ image_data.seek(current_pos)+ elif isinstance(image_data, BufferedReader):+ # Save current position+ current_pos = image_data.tell()+ image_data.seek(0)+ bytes_data = image_data.read(100)+ # Restore position+ image_data.seek(current_pos)+ elif isinstance(image_data, bytes):+ bytes_data = image_data[:100]+ else:+ # For other types, try to read if possible+ if hasattr(image_data, "read"):+ current_pos = getattr(image_data, "tell", lambda: 0)()+ if hasattr(image_data, "seek"):+ image_data.seek(0)+ bytes_data = image_data.read(100)+ if hasattr(image_data, "seek"):+ image_data.seek(current_pos)+ else:+ return FILE_MIME_TYPES[FileType.PNG] # Default fallback++ # Use the existing get_image_type function to detect image type+ image_type_str = get_image_type(bytes_data)++ if image_type_str is None:+ return FILE_MIME_TYPES[FileType.PNG] # Default if detection fails++ # Map detected type string to FileType enum and get MIME type+ type_mapping = {+ "png": FileType.PNG,+ "jpeg": FileType.JPEG,+ "gif": FileType.GIF,+ "webp": FileType.WEBP,+ "heic": FileType.HEIC,+ }++ file_type = type_mapping.get(image_type_str)+ if file_type is None:+ return FILE_MIME_TYPES[FileType.PNG] # Default to PNG if unknown++ return FILE_MIME_TYPES[file_type]++ except Exception:+ # If anything goes wrong, default to PNG+ return FILE_MIME_TYPES[FileType.PNG]diff --git a/litellm/llms/openai/image_edit/transformation.py b/litellm/llms/openai/image_edit/transformation.pyindex bcec4aa0296..f1421d4d57f 100644--- a/litellm/llms/openai/image_edit/transformation.py+++ b/litellm/llms/openai/image_edit/transformation.py@@ -5,6 +5,7 @@ import httpxfrom httpx._types import RequestFilesimport litellm+from litellm.images.utils import ImageEditRequestUtilsfrom litellm.llms.base_llm.image_edit.transformation import BaseImageEditConfigfrom litellm.secret_managers.main import get_secret_strfrom litellm.types.images.main import (@@ -85,10 +86,17 @@ class OpenAIImageEditConfig(BaseImageEditConfig):data_without_images = {k: v for k, v in request_dict.items() if k != "image"}files_list: List[Tuple[str, Any]] = []for _image in _images:+ image_content_type: str = ImageEditRequestUtils.get_image_content_type(+ _image+ )if isinstance(_image, BufferedReader):- files_list.append(("image[]", (_image.name, _image, "image/png")))+ files_list.append(+ ("image[]", (_image.name, _image, image_content_type))+ )else:- files_list.append(("image[]", (_image, "image/png")))+ files_list.append(+ ("image[]", ("image.png", _image, image_content_type))+ )return data_without_images, files_listdef transform_image_edit_response(diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex 1802b1f25d3..fec7150cc24 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -250,6 +250,9 @@ class LiteLLMRoutes(enum.Enum):# image generation"/images/generations","/v1/images/generations",+ # image edit+ "/images/edits",+ "/v1/images/edits",# audio transcription"/audio/transcriptions","/v1/audio/transcriptions",diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.pyindex 678dd2693a8..6226c2fa540 100644--- a/litellm/proxy/common_request_processing.py+++ b/litellm/proxy/common_request_processing.py@@ -121,6 +121,7 @@ class ProxyBaseLLMRequestProcessing:"acancel_fine_tuning_job","alist_fine_tuning_jobs","aretrieve_fine_tuning_job",+ "aimage_edit",],version: Optional[str] = None,user_model: Optional[str] = None,@@ -197,6 +198,7 @@ class ProxyBaseLLMRequestProcessing:"_arealtime","aget_responses","adelete_responses",+ "aimage_edit",],proxy_logging_obj: ProxyLogging,general_settings: dict,@@ -215,7 +217,9 @@ class ProxyBaseLLMRequestProcessing:Common request processing logic for both chat completions and responses API endpoints"""verbose_proxy_logger.debug(- "Request received by LiteLLM:\n{}".format(json.dumps(self.data, indent=4)),+ "Request received by LiteLLM:\n{}".format(+ json.dumps(self.data, indent=4, default=str)+ ),)self.data, logging_obj = await self.common_processing_pre_call_logic(diff --git a/litellm/proxy/image_endpoints/endpoints.py b/litellm/proxy/image_endpoints/endpoints.pynew file mode 100644index 00000000000..4dd5811b2b4--- /dev/null+++ b/litellm/proxy/image_endpoints/endpoints.py@@ -0,0 +1,260 @@+import asyncio+import traceback+from typing import List++import orjson+from fastapi import APIRouter, Depends, File, HTTPException, Request, Response, status+from fastapi.responses import ORJSONResponse++import litellm+from litellm._logging import verbose_proxy_logger+from litellm.proxy._types import *+from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth, user_api_key_auth+from litellm.proxy.common_request_processing import ProxyBaseLLMRequestProcessing+from litellm.proxy.route_llm_request import route_request++router = APIRouter()++import io++from fastapi import UploadFile+++async def uploadfile_to_bytesio(upload: UploadFile) -> io.BytesIO:+ """+ Read a FastAPI UploadFile into a BytesIO and set .name so OpenAI SDK+ infers filename/content-type correctly.+ """+ data = await upload.read()+ buffer = io.BytesIO(data)+ buffer.name = upload.filename+ return buffer+++async def batch_to_bytesio(+ uploads: Optional[List[UploadFile]],+) -> Optional[List[io.BytesIO]]:+ """+ Convert a list of UploadFiles to a list of BytesIO buffers, or None.+ """+ if not uploads:+ return None+ return [await uploadfile_to_bytesio(u) for u in uploads]+++ "/v1/images/generations",+ dependencies=[Depends(user_api_key_auth)],+ response_class=ORJSONResponse,+ tags=["images"],+)+ "/images/generations",+ dependencies=[Depends(user_api_key_auth)],+ response_class=ORJSONResponse,+ tags=["images"],+)+async def image_generation(+ request: Request,+ fastapi_response: Response,+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ from litellm.proxy.proxy_server import (+ add_litellm_data_to_request,+ general_settings,+ llm_router,+ proxy_config,+ proxy_logging_obj,+ user_model,+ version,+ )++ data = {}+ try:+ # Use orjson to parse JSON data, orjson speeds up requests significantly+ body = await request.body()+ data = orjson.loads(body)++ # Include original request and headers in the data+ data = await add_litellm_data_to_request(+ data=data,+ request=request,+ general_settings=general_settings,+ user_api_key_dict=user_api_key_dict,+ version=version,+ proxy_config=proxy_config,+ )++ data["model"] = (+ general_settings.get("image_generation_model", None) # server default+ or user_model # model name passed via cli args+ or data.get("model", None) # default passed in http request+ )+ if user_model:+ data["model"] = user_model++ ### MODEL ALIAS MAPPING ###+ # check if model name in model alias map+ # get the actual model name+ if data["model"] in litellm.model_alias_map:+ data["model"] = litellm.model_alias_map[data["model"]]++ ### CALL HOOKS ### - modify incoming data / reject request before calling the model+ data = await proxy_logging_obj.pre_call_hook(+ user_api_key_dict=user_api_key_dict, data=data, call_type="image_generation"+ )++ ## ROUTE TO CORRECT ENDPOINT ##+ llm_call = await route_request(+ data=data,+ route_type="aimage_generation",+ llm_router=llm_router,+ user_model=user_model,+ )+ response = await llm_call++ ### ALERTING ###+ asyncio.create_task(+ proxy_logging_obj.update_request_status(+ litellm_call_id=data.get("litellm_call_id", ""), status="success"+ )+ )+ ### RESPONSE HEADERS ###+ hidden_params = getattr(response, "_hidden_params", {}) or {}+ model_id = hidden_params.get("model_id", None) or ""+ cache_key = hidden_params.get("cache_key", None) or ""+ api_base = hidden_params.get("api_base", None) or ""+ response_cost = hidden_params.get("response_cost", None) or ""+ litellm_call_id = hidden_params.get("litellm_call_id", None) or ""++ fastapi_response.headers.update(+ ProxyBaseLLMRequestProcessing.get_custom_headers(+ user_api_key_dict=user_api_key_dict,+ model_id=model_id,+ cache_key=cache_key,+ api_base=api_base,+ version=version,+ response_cost=response_cost,+ model_region=getattr(user_api_key_dict, "allowed_model_region", ""),+ call_id=litellm_call_id,+ request_data=data,+ hidden_params=hidden_params,+ )+ )++ return response+ except Exception as e:+ await proxy_logging_obj.post_call_failure_hook(+ user_api_key_dict=user_api_key_dict, original_exception=e, request_data=data+ )+ verbose_proxy_logger.error(+ "litellm.proxy.proxy_server.image_generation(): Exception occured - {}".format(+ str(e)+ )+ )+ verbose_proxy_logger.debug(traceback.format_exc())+ if isinstance(e, HTTPException):+ raise ProxyException(+ message=getattr(e, "message", str(e)),+ type=getattr(e, "type", "None"),+ param=getattr(e, "param", "None"),+ code=getattr(e, "status_code", status.HTTP_400_BAD_REQUEST),+ )+ else:+ error_msg = f"{str(e)}"+ raise ProxyException(+ message=getattr(e, "message", error_msg),+ type=getattr(e, "type", "None"),+ param=getattr(e, "param", "None"),+ openai_code=getattr(e, "code", None),+ code=getattr(e, "status_code", 500),+ )+++ "/v1/images/edits",+ dependencies=[Depends(user_api_key_auth)],+ tags=["images"],+)+ "/images/edits",+ dependencies=[Depends(user_api_key_auth)],+ tags=["images"],+)+async def image_edit_api(+ request: Request,+ fastapi_response: Response,+ image: List[UploadFile] = File(...),+ mask: Optional[List[UploadFile]] = File(None),+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):+ """+ Follows the OpenAI Images API spec: https://platform.openai.com/docs/api-reference/images/create++ ```bash+ curl -s -D >(grep -i x-request-id >&2) \+ -o >(jq -r '.data[0].b64_json' | base64 --decode > gift-basket.png) \+ -X POST "http://localhost:4000/v1/images/edits" \+ -H "Authorization: Bearer sk-1234" \+ -F "model=gpt-image-1" \+ -F "image[][email protected]" \+ -F 'prompt=Create a studio ghibli image of this'+ ```+ """+ from litellm.proxy.proxy_server import (+ _read_request_body,+ general_settings,+ llm_router,+ proxy_config,+ proxy_logging_obj,+ select_data_generator,+ user_api_base,+ user_max_tokens,+ user_model,+ user_request_timeout,+ user_temperature,+ version,+ )++ #########################################################+ # Read request body and convert UploadFiles to BytesIO+ #########################################################+ data = await _read_request_body(request=request)+ image_files = await batch_to_bytesio(image)+ mask_files = await batch_to_bytesio(mask)+ if image_files:+ data["image"] = image_files+ if mask_files:+ data["mask"] = mask_files++ #########################################################+ # Process request+ #########################################################++ processor = ProxyBaseLLMRequestProcessing(data=data)+ try:+ return await processor.base_process_llm_request(+ request=request,+ fastapi_response=fastapi_response,+ user_api_key_dict=user_api_key_dict,+ route_type="aimage_edit",+ proxy_logging_obj=proxy_logging_obj,+ llm_router=llm_router,+ general_settings=general_settings,+ proxy_config=proxy_config,+ select_data_generator=select_data_generator,+ model=None,+ user_model=user_model,+ user_temperature=user_temperature,+ user_request_timeout=user_request_timeout,+ user_max_tokens=user_max_tokens,+ user_api_base=user_api_base,+ version=version,+ )+ except Exception as e:+ raise await processor._handle_llm_api_exception(+ e=e,+ user_api_key_dict=user_api_key_dict,+ proxy_logging_obj=proxy_logging_obj,+ version=version,+ )diff --git a/litellm/proxy/proxy_config.yaml b/litellm/proxy/proxy_config.yamlindex 4250897f4ac..5af761a96de 100644--- a/litellm/proxy/proxy_config.yaml+++ b/litellm/proxy/proxy_config.yaml@@ -1,6 +1,4 @@model_list:- - model_name: openai/gpt-4o+ - model_name: openai/*litellm_params:- model: openai/my-fake-model- api_key: my-fake-key- api_base: https://exampleopenaiendpoint-production.up.railway.app/+ model: openai/*\ No newline at end of filediff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex a3add15669c..5ea29b2ac1d 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -216,6 +216,7 @@ from litellm.proxy.hooks.prompt_injection_detection import (_OPTIONAL_PromptInjectionDetection,)from litellm.proxy.hooks.proxy_track_cost_callback import _ProxyDBLogger+from litellm.proxy.image_endpoints.endpoints import router as image_routerfrom litellm.proxy.litellm_pre_call_utils import add_litellm_data_to_requestfrom litellm.proxy.management_endpoints.budget_management_endpoints import (router as budget_management_router,@@ -4018,126 +4019,6 @@ async def embeddings( # noqa: PLR0915)- "/v1/images/generations",- dependencies=[Depends(user_api_key_auth)],- response_class=ORJSONResponse,- tags=["images"],-)- "/images/generations",- dependencies=[Depends(user_api_key_auth)],- response_class=ORJSONResponse,- tags=["images"],-)-async def image_generation(- request: Request,- fastapi_response: Response,- user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),-):- global proxy_logging_obj- data = {}- try:- # Use orjson to parse JSON data, orjson speeds up requests significantly- body = await request.body()- data = orjson.loads(body)-- # Include original request and headers in the data- data = await add_litellm_data_to_request(- data=data,- request=request,- general_settings=general_settings,- user_api_key_dict=user_api_key_dict,- version=version,- proxy_config=proxy_config,- )-- data["model"] = (- general_settings.get("image_generation_model", None) # server default- or user_model # model name passed via cli args- or data.get("model", None) # default passed in http request- )- if user_model:- data["model"] = user_model-- ### MODEL ALIAS MAPPING ###- # check if model name in model alias map- # get the actual model name- if data["model"] in litellm.model_alias_map:- data["model"] = litellm.model_alias_map[data["model"]]-- ### CALL HOOKS ### - modify incoming data / reject request before calling the model- data = await proxy_logging_obj.pre_call_hook(- user_api_key_dict=user_api_key_dict, data=data, call_type="image_generation"- )-- ## ROUTE TO CORRECT ENDPOINT ##- llm_call = await route_request(- data=data,- route_type="aimage_generation",- llm_router=llm_router,- user_model=user_model,- )- response = await llm_call-- ### ALERTING ###- asyncio.create_task(- proxy_logging_obj.update_request_status(- litellm_call_id=data.get("litellm_call_id", ""), status="success"- )- )- ### RESPONSE HEADERS ###- hidden_params = getattr(response, "_hidden_params", {}) or {}- model_id = hidden_params.get("model_id", None) or ""- cache_key = hidden_params.get("cache_key", None) or ""- api_base = hidden_params.get("api_base", None) or ""- response_cost = hidden_params.get("response_cost", None) or ""- litellm_call_id = hidden_params.get("litellm_call_id", None) or ""-- fastapi_response.headers.update(- ProxyBaseLLMRequestProcessing.get_custom_headers(- user_api_key_dict=user_api_key_dict,- model_id=model_id,- cache_key=cache_key,- api_base=api_base,- version=version,- response_cost=response_cost,- model_region=getattr(user_api_key_dict, "allowed_model_region", ""),- call_id=litellm_call_id,- request_data=data,- hidden_params=hidden_params,- )- )-- return response- except Exception as e:- await proxy_logging_obj.post_call_failure_hook(- user_api_key_dict=user_api_key_dict, original_exception=e, request_data=data- )- verbose_proxy_logger.error(- "litellm.proxy.proxy_server.image_generation(): Exception occured - {}".format(- str(e)- )- )- verbose_proxy_logger.debug(traceback.format_exc())- if isinstance(e, HTTPException):- raise ProxyException(- message=getattr(e, "message", str(e)),- type=getattr(e, "type", "None"),- param=getattr(e, "param", "None"),- code=getattr(e, "status_code", status.HTTP_400_BAD_REQUEST),- )- else:- error_msg = f"{str(e)}"- raise ProxyException(- message=getattr(e, "message", error_msg),- type=getattr(e, "type", "None"),- param=getattr(e, "param", "None"),- openai_code=getattr(e, "code", None),- code=getattr(e, "status_code", 500),- )--@router.post("/v1/audio/speech",dependencies=[Depends(user_api_key_auth)],@@ -8374,6 +8255,7 @@ app.include_router(router)app.include_router(response_router)app.include_router(batches_router)app.include_router(rerank_router)+app.include_router(image_router)app.include_router(fine_tuning_router)app.include_router(credential_router)app.include_router(llm_passthrough_router)diff --git a/litellm/proxy/route_llm_request.py b/litellm/proxy/route_llm_request.pyindex ad570f2f09f..0d8f04dbc57 100644--- a/litellm/proxy/route_llm_request.py+++ b/litellm/proxy/route_llm_request.py@@ -22,6 +22,7 @@ ROUTE_ENDPOINT_MAPPING = {"amoderation": "/moderations","arerank": "/rerank","aresponses": "/responses",+ "aimage_edit": "/images/edits",}@@ -69,6 +70,7 @@ async def route_request("aget_responses","adelete_responses","_arealtime", # private function for realtime API+ "aimage_edit",],):"""diff --git a/litellm/router.py b/litellm/router.pyindex 6bcfea3a953..5e341bf789b 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -771,6 +771,9 @@ class Router:self.afile_list = self.factory_function(litellm.afile_list, call_type="alist_files")+ self.aimage_edit = self.factory_function(+ litellm.aimage_edit, call_type="aimage_edit"+ )def validate_fallbacks(self, fallback_param: Optional[List]):"""@@ -3193,6 +3196,7 @@ class Router:"alist_fine_tuning_jobs","aretrieve_fine_tuning_job","alist_files",+ "aimage_edit",] = "assistants",):"""@@ -3246,6 +3250,7 @@ class Router:"alist_fine_tuning_jobs","aretrieve_fine_tuning_job","alist_files",+ "aimage_edit",):return await self._ageneric_api_call_with_fallbacks(original_function=original_function,diff --git a/tests/image_gen_tests/test_image_edits.py b/tests/image_gen_tests/test_image_edits.pyindex 1e16120122f..649006dea03 100644--- a/tests/image_gen_tests/test_image_edits.py+++ b/tests/image_gen_tests/test_image_edits.py@@ -1,11 +1,10 @@--import loggingimport osimport sysimport tracebackimport pytestimport base64+from io import BytesIOsys.path.insert(0, os.path.abspath("../..")@@ -21,7 +20,16 @@ TEST_IMAGES = [open(os.path.join(pwd, "litellm_site.png"), "rb"),][email protected]("sync_mode", [True])+def get_test_images_as_bytesio():+ """Helper function to get test images as BytesIO objects"""+ bytesio_images = []+ for image_path in ["ishaan_github.png", "litellm_site.png"]:+ with open(os.path.join(pwd, image_path), "rb") as f:+ image_bytes = f.read()+ bytesio_images.append(BytesIO(image_bytes))+ return bytesio_images+[email protected]("sync_mode", [True, False])@pytest.mark.flaky(retries=3, delay=2)@pytest.mark.asyncioasync def test_openai_image_edit_litellm_sdk(sync_mode):@@ -49,12 +57,89 @@ async def test_openai_image_edit_litellm_sdk(sync_mode):# Validate the response meets expected schemaImageResponse.model_validate(result)- if isinstance(result, ImageResponse):+ 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+++[email protected](retries=3, delay=2)+async def test_openai_image_edit_litellm_router():+ 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.+ """+ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-image-1",+ "litellm_params": {+ "model": "gpt-image-1",+ },+ }+ ]+ )+ result = await router.aimage_edit(+ prompt=prompt,+ model="gpt-image-1",+ image=TEST_IMAGES,+ )+ 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+[email protected](retries=3, delay=2)+async def test_openai_image_edit_with_bytesio():+ """Test image editing using BytesIO objects instead of file readers"""+ 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.+ """++ # Get images as BytesIO objects+ bytesio_images = get_test_images_as_bytesio()++ result = await aimage_edit(+ prompt=prompt,+ model="gpt-image-1",+ image=bytesio_images,+ )+ print("result from image edit with BytesIO", 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- image_bytes = base64.b64decode(image_base64)+ 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)+ # Save the image to a file+ with open("test_image_edit_bytesio.png", "wb") as f:+ f.write(image_bytes)except litellm.ContentPolicyViolationError as e:passdiff --git a/tests/proxy_admin_ui_tests/test_key_management.py b/tests/proxy_admin_ui_tests/test_key_management.pyindex b3bb65e3406..766d4835b3a 100644--- a/tests/proxy_admin_ui_tests/test_key_management.py+++ b/tests/proxy_admin_ui_tests/test_key_management.py@@ -53,7 +53,6 @@ from litellm.proxy.proxy_server import (chat_completion,completion,embeddings,- image_generation,model_list,moderations,user_api_key_auth,diff --git a/tests/proxy_admin_ui_tests/test_role_based_access.py b/tests/proxy_admin_ui_tests/test_role_based_access.pyindex a1a3a406da2..a1c4e9a399a 100644--- a/tests/proxy_admin_ui_tests/test_role_based_access.py+++ b/tests/proxy_admin_ui_tests/test_role_based_access.py@@ -55,7 +55,6 @@ from litellm.proxy.proxy_server import (chat_completion,completion,embeddings,- image_generation,model_list,moderations,user_api_key_auth,diff --git a/tests/proxy_admin_ui_tests/test_usage_endpoints.py b/tests/proxy_admin_ui_tests/test_usage_endpoints.pyindex cd704e49ccb..ab5e5fb834c 100644--- a/tests/proxy_admin_ui_tests/test_usage_endpoints.py+++ b/tests/proxy_admin_ui_tests/test_usage_endpoints.py@@ -64,7 +64,6 @@ from litellm.proxy.proxy_server import (chat_completion,completion,embeddings,- image_generation,model_list,moderations,user_api_key_auth,diff --git a/tests/proxy_unit_tests/test_audit_logs_proxy.py b/tests/proxy_unit_tests/test_audit_logs_proxy.pyindex 02303e13db0..a4506950dd1 100644--- a/tests/proxy_unit_tests/test_audit_logs_proxy.py+++ b/tests/proxy_unit_tests/test_audit_logs_proxy.py@@ -34,7 +34,6 @@ from litellm.proxy.proxy_server import (chat_completion,completion,embeddings,- image_generation,model_list,moderations,user_api_key_auth,diff --git a/tests/proxy_unit_tests/test_e2e_pod_lock_manager.py b/tests/proxy_unit_tests/test_e2e_pod_lock_manager.pyindex d007c3d73fd..8db51e5aad1 100644--- a/tests/proxy_unit_tests/test_e2e_pod_lock_manager.py+++ b/tests/proxy_unit_tests/test_e2e_pod_lock_manager.py@@ -55,7 +55,6 @@ from litellm.proxy.proxy_server import (chat_completion,completion,embeddings,- image_generation,model_list,moderations,user_api_key_auth,diff --git a/tests/proxy_unit_tests/test_key_generate_prisma.py b/tests/proxy_unit_tests/test_key_generate_prisma.pyindex f34d9478c16..cff4747bc0e 100644--- a/tests/proxy_unit_tests/test_key_generate_prisma.py+++ b/tests/proxy_unit_tests/test_key_generate_prisma.py@@ -73,7 +73,6 @@ from litellm.proxy.proxy_server import (chat_completion,completion,embeddings,- image_generation,model_list,moderations,user_api_key_auth,diff --git a/ui/litellm-dashboard/src/components/chat_ui.tsx b/ui/litellm-dashboard/src/components/chat_ui.tsxindex 78d5a7e6336..5fa575aad4e 100644--- a/ui/litellm-dashboard/src/components/chat_ui.tsx+++ b/ui/litellm-dashboard/src/components/chat_ui.tsx@@ -24,9 +24,10 @@ import {} from "@tremor/react";import { v4 as uuidv4 } from 'uuid';-import { message, Select, Spin, Typography, Tooltip, Input } from "antd";+import { message, Select, Spin, Typography, Tooltip, Input, Upload } from "antd";import { makeOpenAIChatCompletionRequest } from "./chat_ui/llm_calls/chat_completion";import { makeOpenAIImageGenerationRequest } from "./chat_ui/llm_calls/image_generation";+import { makeOpenAIImageEditsRequest } from "./chat_ui/llm_calls/image_edits";import { makeOpenAIResponsesRequest } from "./chat_ui/llm_calls/responses_api";import { fetchAvailableModels, ModelGroup } from "./chat_ui/llm_calls/fetch_models";import { litellmModeMapping, ModelMode, EndpointType, getEndpointType } from "./chat_ui/mode_endpoint_mapping";@@ -52,10 +53,13 @@ import {TagsOutlined,DatabaseOutlined,InfoCircleOutlined,- SafetyOutlined+ SafetyOutlined,+ UploadOutlined,+ PictureOutlined} from "@ant-design/icons";const { TextArea } = Input;+const { Dragger } = Upload;interface ChatUIProps {accessToken: string | null;@@ -91,6 +95,8 @@ const ChatUI: React.FC<ChatUIProps> = ({const [selectedVectorStores, setSelectedVectorStores] = useState<string[]>([]);const [selectedGuardrails, setSelectedGuardrails] = useState<string[]>([]);const [messageTraceId, setMessageTraceId] = useState<string | null>(null);+ const [uploadedImage, setUploadedImage] = useState<File | null>(null);+ const [imagePreviewUrl, setImagePreviewUrl] = useState<string | null>(null);const chatEndRef = useRef<HTMLDivElement>(null);@@ -288,9 +294,30 @@ const ChatUI: React.FC<ChatUIProps> = ({}};+ const handleImageUpload = (file: File) => {+ setUploadedImage(file);+ const previewUrl = URL.createObjectURL(file);+ setImagePreviewUrl(previewUrl);+ return false; // Prevent default upload behavior+ };++ const handleRemoveImage = () => {+ if (imagePreviewUrl) {+ URL.revokeObjectURL(imagePreviewUrl);+ }+ setUploadedImage(null);+ setImagePreviewUrl(null);+ };+const handleSendMessage = async () => {if (inputMessage.trim() === "") return;+ // For image edits, require both image and prompt+ if (endpointType === EndpointType.IMAGE_EDITS && !uploadedImage) {+ message.error("Please upload an image for editing");+ return;+ }+if (!token || !userRole || !userID) {return;}@@ -349,6 +376,19 @@ const ChatUI: React.FC<ChatUIProps> = ({selectedTags,signal);+ } else if (endpointType === EndpointType.IMAGE_EDITS) {+ // For image edits+ if (uploadedImage) {+ await makeOpenAIImageEditsRequest(+ uploadedImage,+ inputMessage,+ (imageUrl, model) => updateImageUI(imageUrl, model),+ selectedModel,+ effectiveApiKey,+ selectedTags,+ signal+ );+ }} else if (endpointType === EndpointType.RESPONSES) {// Create chat history for API call - strip out model field and isImage fieldconst apiChatHistory = [...chatHistory.filter(msg => !msg.isImage).map(({ role, content }) => ({ role, content })), newUserMessage];@@ -379,6 +419,10 @@ const ChatUI: React.FC<ChatUIProps> = ({} finally {setIsLoading(false);abortControllerRef.current = null;+ // Clear image after successful request for image edits+ if (endpointType === EndpointType.IMAGE_EDITS) {+ handleRemoveImage();+ }}setInputMessage("");@@ -387,6 +431,7 @@ const ChatUI: React.FC<ChatUIProps> = ({const clearChatHistory = () => {setChatHistory([]);setMessageTraceId(null);+ handleRemoveImage(); // Clear any uploaded imagesmessage.success("Chat history cleared.");};@@ -675,6 +720,42 @@ const ChatUI: React.FC<ChatUIProps> = ({</div><div className="p-4 border-t border-gray-200 bg-white">+ {/* Image Upload Section for Image Edits */}+ {endpointType === EndpointType.IMAGE_EDITS && (+ <div className="mb-4">+ {!uploadedImage ? (+ <Dragger+ beforeUpload={handleImageUpload}+ accept="image/*"+ showUploadList={false}+ className="border-dashed border-2 border-gray-300 rounded-lg p-4"+ >+ <p className="ant-upload-drag-icon">+ <PictureOutlined style={{ fontSize: '24px', color: '#666' }} />+ </p>+ <p className="ant-upload-text text-sm">Click or drag image to upload</p>+ <p className="ant-upload-hint text-xs text-gray-500">+ Support for PNG, JPG, JPEG formats+ </p>+ </Dragger>+ ) : (+ <div className="relative inline-block">+ <img+ src={imagePreviewUrl || ''}+ alt="Upload preview"+ className="max-w-32 max-h-32 rounded-md border border-gray-200 object-cover"+ />+ <button+ className="absolute top-1 right-1 bg-white shadow-sm border border-gray-200 rounded px-1 py-1 text-red-500 hover:bg-red-50 text-xs"+ onClick={handleRemoveImage}+ >+ <DeleteOutlined />+ </button>+ </div>+ )}+ </div>+ )}+<div className="flex items-center"><TextAreavalue={inputMessage}@@ -683,6 +764,8 @@ const ChatUI: React.FC<ChatUIProps> = ({placeholder={endpointType === EndpointType.CHAT || endpointType === EndpointType.RESPONSES? "Type your message... (Shift+Enter for new line)"+ : endpointType === EndpointType.IMAGE_EDITS+ ? "Describe how you want to edit the image...": "Describe the image you want to generate..."}disabled={isLoading}@@ -704,7 +787,8 @@ const ChatUI: React.FC<ChatUIProps> = ({className="ml-2 text-white"icon={endpointType === EndpointType.CHAT ? SendOutlined : RobotOutlined}>- {endpointType === EndpointType.CHAT ? "Send" : "Generate"}+ {endpointType === EndpointType.CHAT ? "Send" :+ endpointType === EndpointType.IMAGE_EDITS ? "Edit" : "Generate"}</Button>)}</div>diff --git a/ui/litellm-dashboard/src/components/chat_ui/EndpointSelector.tsx b/ui/litellm-dashboard/src/components/chat_ui/EndpointSelector.tsxindex 12d5acbc70d..73e6c5d7aa0 100644--- a/ui/litellm-dashboard/src/components/chat_ui/EndpointSelector.tsx+++ b/ui/litellm-dashboard/src/components/chat_ui/EndpointSelector.tsx@@ -22,6 +22,7 @@ const EndpointSelector: React.FC<EndpointSelectorProps> = ({{ value: EndpointType.CHAT, label: '/v1/chat/completions' },{ value: EndpointType.RESPONSES, label: '/v1/responses' },{ value: EndpointType.IMAGE, label: '/v1/images/generations' },+ { value: EndpointType.IMAGE_EDITS, label: '/v1/images/edits' },];return (diff --git a/ui/litellm-dashboard/src/components/chat_ui/llm_calls/image_edits.tsx b/ui/litellm-dashboard/src/components/chat_ui/llm_calls/image_edits.tsxnew file mode 100644index 00000000000..271d945e917--- /dev/null+++ b/ui/litellm-dashboard/src/components/chat_ui/llm_calls/image_edits.tsx@@ -0,0 +1,62 @@+import openai from "openai";+import { message } from "antd";++export async function makeOpenAIImageEditsRequest(+ imageFile: File,+ prompt: string,+ updateUI: (imageUrl: string, model: string) => void,+ selectedModel: string,+ accessToken: string,+ tags?: string[],+ signal?: AbortSignal+) {+ // base url should be the current base_url+ const isLocal = process.env.NODE_ENV === "development";+ if (isLocal !== true) {+ console.log = function () {};+ }+ console.log("isLocal:", isLocal);+ const proxyBaseUrl = isLocal+ ? "http://localhost:4000"+ : window.location.origin;++ const client = new openai.OpenAI({+ apiKey: accessToken,+ baseURL: proxyBaseUrl,+ dangerouslyAllowBrowser: true,+ defaultHeaders: tags && tags.length > 0 ? { 'x-litellm-tags': tags.join(',') } : undefined,+ });++ try {+ const response = await client.images.edit({+ model: selectedModel,+ image: imageFile,+ prompt: prompt,+ }, { signal });++ console.log(response.data);++ if (response.data && response.data[0]) {+ // Handle either URL or base64 data from response+ if (response.data[0].url) {+ // Use the URL directly+ updateUI(response.data[0].url, selectedModel);+ } else if (response.data[0].b64_json) {+ // Convert base64 to data URL format+ const base64Data = response.data[0].b64_json;+ updateUI(`data:image/png;base64,${base64Data}`, selectedModel);+ } else {+ throw new Error("No image data found in response");+ }+ } else {+ throw new Error("Invalid response format");+ }+ } catch (error) {+ if (signal?.aborted) {+ console.log("Image edits request was cancelled");+ } else {+ message.error(`Error occurred while editing image. Please try again. Error: ${error}`, 20);+ }+ throw error; // Re-throw to allow the caller to handle the error+ }+}\ No newline at end of filediff --git a/ui/litellm-dashboard/src/components/chat_ui/mode_endpoint_mapping.tsx b/ui/litellm-dashboard/src/components/chat_ui/mode_endpoint_mapping.tsxindex ea868318420..bcd030199d2 100644--- a/ui/litellm-dashboard/src/components/chat_ui/mode_endpoint_mapping.tsx+++ b/ui/litellm-dashboard/src/components/chat_ui/mode_endpoint_mapping.tsx@@ -5,6 +5,7 @@ export enum ModelMode {IMAGE_GENERATION = "image_generation",CHAT = "chat",RESPONSES = "responses",+ IMAGE_EDITS = "image_edits",// add additional modes as needed}@@ -13,6 +14,7 @@ export enum ModelMode {IMAGE = "image",CHAT = "chat",RESPONSES = "responses",+ IMAGE_EDITS = "image_edits",// add additional endpoint types if required}@@ -21,6 +23,7 @@ export enum ModelMode {[ModelMode.IMAGE_GENERATION]: EndpointType.IMAGE,[ModelMode.CHAT]: EndpointType.CHAT,[ModelMode.RESPONSES]: EndpointType.RESPONSES,+ [ModelMode.IMAGE_EDITS]: EndpointType.IMAGE_EDITS,};export const getEndpointType = (mode: string): EndpointType => {