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] New provider - Add Azure BFL FLux for image edits (#18766)
Ishaan Jaff929af510fa12
diff --git a/docs/my-website/docs/providers/azure_ai_img.md b/docs/my-website/docs/providers/azure_ai_img.mdindex 6434856fd2a..513bbe858d0 100644--- a/docs/my-website/docs/providers/azure_ai_img.md+++ b/docs/my-website/docs/providers/azure_ai_img.md@@ -12,7 +12,7 @@ Azure AI provides powerful image generation capabilities using FLUX models from| Description | Azure AI Image Generation uses FLUX models to generate high-quality images from text descriptions. || Provider Route on LiteLLM | `azure_ai/` || Provider Doc | [Azure AI FLUX Models ↗](https://techcommunity.microsoft.com/blog/azure-ai-foundry-blog/black-forest-labs-flux-1-kontext-pro-and-flux1-1-pro-now-available-in-azure-ai-f/4434659) |-| Supported Operations | [`/images/generations`](#image-generation) |+| Supported Operations | [`/images/generations`](#image-generation), [`/images/edits`](#image-editing) |## Setup@@ -275,6 +275,103 @@ curl --location 'http://localhost:4000/v1/images/generations' \</TabItem></Tabs>+## Image Editing++FLUX 2 Pro supports image editing by passing an input image along with a prompt describing the desired modifications.++### Usage - LiteLLM Python SDK++<Tabs>+<TabItem value="basic-edit" label="Basic Image Edit">++```python showLineNumbers title="Basic Image Editing with FLUX 2 Pro"+import litellm+import os++# Set your API credentials+os.environ["AZURE_AI_API_KEY"] = "your-api-key-here"+os.environ["AZURE_AI_API_BASE"] = "your-azure-ai-endpoint" # e.g., https://litellm-ci-cd-prod.services.ai.azure.com++# Edit an existing image+response = litellm.image_edit(+ model="azure_ai/flux.2-pro",+ prompt="Add a red hat to the subject",+ image=open("input_image.png", "rb"),+ api_base=os.environ["AZURE_AI_API_BASE"],+ api_key=os.environ["AZURE_AI_API_KEY"],+ api_version="preview",+)++print(response.data[0].b64_json) # FLUX 2 returns base64 encoded images+```++</TabItem>++<TabItem value="async-edit" label="Async Image Edit">++```python showLineNumbers title="Async Image Editing"+import litellm+import asyncio+import os++async def edit_image():+ os.environ["AZURE_AI_API_KEY"] = "your-api-key-here"+ os.environ["AZURE_AI_API_BASE"] = "your-azure-ai-endpoint"++ response = await litellm.aimage_edit(+ model="azure_ai/flux.2-pro",+ prompt="Change the background to a sunset beach",+ image=open("input_image.png", "rb"),+ api_base=os.environ["AZURE_AI_API_BASE"],+ api_key=os.environ["AZURE_AI_API_KEY"],+ api_version="preview",+ )++ return response++asyncio.run(edit_image())+```++</TabItem>+</Tabs>++### Usage - LiteLLM Proxy Server++<Tabs>+<TabItem value="curl-edit" label="cURL">++```bash showLineNumbers title="Image Edit via Proxy - cURL"+curl --location 'http://localhost:4000/v1/images/edits' \+--header 'Authorization: Bearer sk-1234' \+--form 'model="azure-flux-2-pro"' \+--form 'prompt="Add sunglasses to the person"' \+--form 'image=@"input_image.png"'+```++</TabItem>++<TabItem value="openai-sdk-edit" label="OpenAI SDK">++```python showLineNumbers title="Image Edit via Proxy - OpenAI SDK"+from openai import OpenAI++client = OpenAI(+ base_url="http://localhost:4000",+ api_key="sk-1234"+)++response = client.images.edit(+ model="azure-flux-2-pro",+ prompt="Make the sky more dramatic with storm clouds",+ image=open("input_image.png", "rb"),+)++print(response.data[0].b64_json)+```++</TabItem>+</Tabs>+## Supported ParametersAzure AI Image Generation supports the following OpenAI-compatible parameters:diff --git a/litellm/llms/azure_ai/image_edit/__init__.py b/litellm/llms/azure_ai/image_edit/__init__.pyindex e0e57bec403..e3acd610446 100644--- a/litellm/llms/azure_ai/image_edit/__init__.py+++ b/litellm/llms/azure_ai/image_edit/__init__.py@@ -1,15 +1,28 @@+from litellm.llms.azure_ai.image_generation.flux_transformation import (+ AzureFoundryFluxImageGenerationConfig,+)from litellm.llms.base_llm.image_edit.transformation import BaseImageEditConfig+from .flux2_transformation import AzureFoundryFlux2ImageEditConfigfrom .transformation import AzureFoundryFluxImageEditConfig-__all__ = ["AzureFoundryFluxImageEditConfig"]+__all__ = ["AzureFoundryFluxImageEditConfig", "AzureFoundryFlux2ImageEditConfig"]def get_azure_ai_image_edit_config(model: str) -> BaseImageEditConfig:- model = model.lower()- model = model.replace("-", "")- model = model.replace("_", "")- if model == "" or "flux" in model: # empty model is flux+ """+ Get the appropriate image edit config for an Azure AI model.++ - FLUX 2 models use JSON with base64 image+ - FLUX 1 models use multipart/form-data+ """+ # Check if it's a FLUX 2 model+ if AzureFoundryFluxImageGenerationConfig.is_flux2_model(model):+ return AzureFoundryFlux2ImageEditConfig()++ # Default to FLUX 1 config for other FLUX models+ model_normalized = model.lower().replace("-", "").replace("_", "")+ if model_normalized == "" or "flux" in model_normalized:return AzureFoundryFluxImageEditConfig()- else:- raise ValueError(f"Model {model} is not supported for Azure AI image editing.")++ raise ValueError(f"Model {model} is not supported for Azure AI image editing.")diff --git a/litellm/llms/azure_ai/image_edit/flux2_transformation.py b/litellm/llms/azure_ai/image_edit/flux2_transformation.pynew file mode 100644index 00000000000..caa39056675--- /dev/null+++ b/litellm/llms/azure_ai/image_edit/flux2_transformation.py@@ -0,0 +1,167 @@+import base64+from io import BufferedReader+from typing import Any, Dict, Optional, Tuple++from httpx._types import RequestFiles++import litellm+from litellm.llms.azure_ai.common_utils import AzureFoundryModelInfo+from litellm.llms.azure_ai.image_generation.flux_transformation import (+ AzureFoundryFluxImageGenerationConfig,+)+from litellm.llms.openai.image_edit.transformation import OpenAIImageEditConfig+from litellm.secret_managers.main import get_secret_str+from litellm.types.images.main import ImageEditOptionalRequestParams+from litellm.types.llms.openai import FileTypes+from litellm.types.router import GenericLiteLLMParams+++class AzureFoundryFlux2ImageEditConfig(OpenAIImageEditConfig):+ """+ Azure AI Foundry FLUX 2 image edit config++ Supports FLUX 2 models (e.g., flux.2-pro) for image editing.+ Uses the same /providers/blackforestlabs/v1/flux-2-pro endpoint as image generation,+ with the image passed as base64 in JSON body.+ """++ def get_supported_openai_params(self, model: str) -> list:+ """+ FLUX 2 supports a subset of OpenAI image edit params+ """+ return [+ "prompt",+ "image",+ "model",+ "n",+ "size",+ ]++ def map_openai_params(+ self,+ image_edit_optional_params: ImageEditOptionalRequestParams,+ model: str,+ drop_params: bool,+ ) -> Dict:+ """+ Map OpenAI params to FLUX 2 params.+ FLUX 2 uses the same param names as OpenAI for supported params.+ """+ mapped_params: Dict[str, Any] = {}+ supported_params = self.get_supported_openai_params(model)++ for key, value in dict(image_edit_optional_params).items():+ if key in supported_params and value is not None:+ mapped_params[key] = value++ return mapped_params++ def use_multipart_form_data(self) -> bool:+ """FLUX 2 uses JSON requests, not multipart/form-data."""+ return False++ def validate_environment(+ self,+ headers: dict,+ model: str,+ api_key: Optional[str] = None,+ ) -> dict:+ """+ Validate Azure AI Foundry environment and set up authentication+ """+ api_key = AzureFoundryModelInfo.get_api_key(api_key)++ if not api_key:+ raise ValueError(+ f"Azure AI API key is required for model {model}. Set AZURE_AI_API_KEY environment variable or pass api_key parameter."+ )++ headers.update(+ {+ "Api-Key": api_key,+ "Content-Type": "application/json",+ }+ )+ return headers++ 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 FLUX 2.++ FLUX 2 uses the same endpoint for generation and editing,+ with the image passed as base64 in the JSON body.+ """+ image_b64 = self._convert_image_to_base64(image)++ # Build request body with required params+ request_body: Dict[str, Any] = {+ "prompt": prompt,+ "image": image_b64,+ "model": model,+ }++ # Add mapped optional params (already filtered by map_openai_params)+ request_body.update(image_edit_optional_request_params)++ # Return JSON body and empty files list (FLUX 2 doesn't use multipart)+ return request_body, []++ def _convert_image_to_base64(self, image: Any) -> str:+ """Convert image file to base64 string"""+ # Handle list of images (take first one)+ if isinstance(image, list):+ if len(image) == 0:+ raise ValueError("Empty image list provided")+ image = image[0]++ if isinstance(image, BufferedReader):+ image_bytes = image.read()+ image.seek(0) # Reset file pointer for potential reuse+ elif isinstance(image, bytes):+ image_bytes = image+ elif hasattr(image, "read"):+ image_bytes = image.read() # type: ignore+ else:+ raise ValueError(f"Unsupported image type: {type(image)}")++ return base64.b64encode(image_bytes).decode("utf-8")++ def get_complete_url(+ self,+ model: str,+ api_base: Optional[str],+ litellm_params: dict,+ ) -> str:+ """+ Constructs a complete URL for Azure AI Foundry FLUX 2 image edits.++ Uses the same /providers/blackforestlabs/v1/flux-2-pro endpoint as image generation.+ """+ api_base = AzureFoundryModelInfo.get_api_base(api_base)++ if api_base is None:+ raise ValueError(+ "Azure AI API base is required. Set AZURE_AI_API_BASE environment variable or pass api_base parameter."+ )++ api_version = (+ litellm_params.get("api_version")+ or litellm.api_version+ or get_secret_str("AZURE_AI_API_VERSION")+ or "preview"+ )++ return AzureFoundryFluxImageGenerationConfig.get_flux2_image_generation_url(+ api_base=api_base,+ model=model,+ api_version=api_version,+ )+diff --git a/litellm/llms/azure_ai/image_edit/transformation.py b/litellm/llms/azure_ai/image_edit/transformation.pyindex 47f612912ce..930b6d4db90 100644--- a/litellm/llms/azure_ai/image_edit/transformation.py+++ b/litellm/llms/azure_ai/image_edit/transformation.py@@ -71,9 +71,11 @@ class AzureFoundryFluxImageEditConfig(OpenAIImageEditConfig):"Azure AI API base is required. Set AZURE_AI_API_BASE environment variable or pass api_base parameter.")- api_version = (litellm_params.get("api_version") or litellm.api_version- or get_secret_str("AZURE_AI_API_VERSION")- )+ api_version = (+ litellm_params.get("api_version")+ or litellm.api_version+ or get_secret_str("AZURE_AI_API_VERSION")+ )if api_version is None:# API version is mandatory for Azure AI Foundryraise ValueError(diff --git a/provider_endpoints_support.json b/provider_endpoints_support.jsonindex c52f71d8578..f671409175a 100644--- a/provider_endpoints_support.json+++ b/provider_endpoints_support.json@@ -284,6 +284,7 @@"responses": true,"embeddings": true,"image_generations": true,+ "image_edits": true,"audio_transcriptions": true,"audio_speech": true,"moderations": true,diff --git a/tests/image_gen_tests/test_image_edits.py b/tests/image_gen_tests/test_image_edits.pyindex 62f8341e0a4..810bd80a5b0 100644--- a/tests/image_gen_tests/test_image_edits.py+++ b/tests/image_gen_tests/test_image_edits.py@@ -143,6 +143,23 @@ class TestOpenAIImageEditDallE2(BaseLLMImageEditTest):}+class TestAzureAIFlux2ImageEdit(BaseLLMImageEditTest):+ """+ Concrete implementation of BaseLLMImageEditTest for Azure AI FLUX 2 image edits.+ FLUX 2 uses JSON with base64 image instead of multipart/form-data.+ """++ def get_base_image_edit_call_args(self) -> dict:+ """Return base call args for Azure AI FLUX 2 image edit"""+ return {+ "model": "azure_ai/flux.2-pro",+ "image": SINGLE_TEST_IMAGE,+ "api_base": os.getenv("AZURE_AI_API_BASE", "https://litellm-ci-cd-prod.services.ai.azure.com"),+ "api_key": os.getenv("AZURE_AI_API_KEY"),+ "api_version": "preview",+ }++@pytest.mark.flaky(retries=3, delay=2)@pytest.mark.asyncioasync def test_openai_image_edit_litellm_router():