Skip to content

Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.

Feature/new models (#841)

Louis Choquel9ae38b612ed2
diff --git a/.pipelex-dev/test_profiles.toml b/.pipelex-dev/test_profiles.toml
index 046187768..cca3a7789 100644
--- a/.pipelex-dev/test_profiles.toml
+++ b/.pipelex-dev/test_profiles.toml
@@ -184,6 +184,7 @@ openai = [
"gpt-5.4-pro",
"gpt-5.4-mini",
"gpt-5.4-nano",
+ "gpt-5.5",
]
# --- OpenAI OSS Models ---
@@ -224,7 +225,7 @@ fal = [
]
# --- OpenAI Models ---
-openai = ["gpt-image-1", "gpt-image-1-mini", "gpt-image-1.5"]
+openai = ["gpt-image-1", "gpt-image-1-mini", "gpt-image-1.5", "gpt-image-2"]
# --- Google Models ---
google = ["nano-banana", "nano-banana-pro", "nano-banana-2"]
diff --git a/.pipelex/inference/backends/azure_openai.toml b/.pipelex/inference/backends/azure_openai.toml
index 49918a036..b1b7e7aa8 100644
--- a/.pipelex/inference/backends/azure_openai.toml
+++ b/.pipelex/inference/backends/azure_openai.toml
@@ -190,14 +190,14 @@ thinking_mode = "manual"
# --- GPT-5.4 Series -----------------------------------------------------------
["gpt-5.4"]
model_id = "gpt-5.4-2026-03-05"
-inputs = ["text", "images"]
+inputs = ["text", "images", "pdf"]
outputs = ["text", "structured"]
costs = { input = 2.5, output = 15.0 }
thinking_mode = "manual"
["gpt-5.4-pro"]
model_id = "gpt-5.4-pro-2026-03-05"
-inputs = ["text", "images"]
+inputs = ["text", "images", "pdf"]
outputs = ["text", "structured"]
costs = { input = 30.0, output = 180.0 }
valued_constraints = { fixed_temperature = 1 }
@@ -205,18 +205,27 @@ thinking_mode = "manual"
["gpt-5.4-mini"]
model_id = "gpt-5.4-mini-2026-03-17"
-inputs = ["text", "images"]
+inputs = ["text", "images", "pdf"]
outputs = ["text", "structured"]
costs = { input = 0.75, output = 4.5 }
thinking_mode = "manual"
["gpt-5.4-nano"]
model_id = "gpt-5.4-nano-2026-03-17"
-inputs = ["text", "images"]
+inputs = ["text", "images", "pdf"]
outputs = ["text", "structured"]
costs = { input = 0.2, output = 1.25 }
thinking_mode = "manual"
+# --- GPT-5.5 Series -----------------------------------------------------------
+["gpt-5.5"]
+model_id = "gpt-5.5-2026-04-24"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 5.0, output = 30.0 }
+valued_constraints = { fixed_temperature = 1 }
+thinking_mode = "manual"
+
################################################################################
# IMAGE GENERATION MODELS
################################################################################
@@ -232,12 +241,14 @@ costs = { input = 10, output = 40 }
[gpt-image-1.rules]
prompt = "positive_only"
-num_images = "gpt"
-aspect_ratio = "gpt"
-background = "gpt"
-inference = "gpt"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_legacy"
+background = "available"
+inference = "gpt_image"
safety_checker = "unavailable"
-output_format = "gpt"
+output_format = "gpt_image_legacy"
+output_compression = "gpt_image_legacy"
+input_fidelity = "gpt_image_legacy"
[gpt-image-1-mini]
sdk = "azure_rest_img_gen"
@@ -249,12 +260,14 @@ costs = { input = 2.5, output = 8 }
[gpt-image-1-mini.rules]
prompt = "positive_only"
-num_images = "gpt"
-aspect_ratio = "gpt"
-background = "gpt"
-inference = "gpt"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_legacy"
+background = "available"
+inference = "gpt_image"
safety_checker = "unavailable"
-output_format = "gpt"
+output_format = "gpt_image_legacy"
+output_compression = "gpt_image_legacy"
+input_fidelity = "gpt_image_legacy"
["gpt-image-1.5"]
sdk = "azure_rest_img_gen"
@@ -266,9 +279,30 @@ costs = { input = 8, output = 32 }
["gpt-image-1.5".rules]
prompt = "positive_only"
-num_images = "gpt"
-aspect_ratio = "gpt"
-background = "gpt"
-inference = "gpt"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_legacy"
+background = "available"
+inference = "gpt_image"
+safety_checker = "unavailable"
+output_format = "gpt_image_legacy"
+output_compression = "gpt_image_legacy"
+input_fidelity = "gpt_image_legacy"
+
+[gpt-image-2]
+sdk = "azure_rest_img_gen"
+model_type = "img_gen"
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 8, output = 30 }
+
+[gpt-image-2.rules]
+prompt = "positive_only"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_2"
+background = "unavailable"
+inference = "gpt_image"
safety_checker = "unavailable"
-output_format = "gpt"
+output_format = "unavailable"
+output_compression = "unavailable"
+input_images = "gpt_image"
+input_fidelity = "unavailable"
diff --git a/.pipelex/inference/backends/fal.toml b/.pipelex/inference/backends/fal.toml
index d79251ef0..2a4d03e12 100644
--- a/.pipelex/inference/backends/fal.toml
+++ b/.pipelex/inference/backends/fal.toml
@@ -38,6 +38,7 @@ outputs = ["image"]
costs = { input = 0.05, output = 0.0 }
[flux-pro.rules]
+model_choice = "model_id"
prompt = "positive_only"
num_images = "fal"
aspect_ratio = "flux"
@@ -53,6 +54,7 @@ outputs = ["image"]
costs = { input = 0.05, output = 0.0 }
["flux-pro/v1.1".rules]
+model_choice = "model_id"
prompt = "positive_only"
num_images = "fal"
aspect_ratio = "flux"
@@ -68,6 +70,7 @@ outputs = ["image"]
costs = { input = 0.06, output = 0.0 }
["flux-pro/v1.1-ultra".rules]
+model_choice = "model_id"
prompt = "positive_only"
num_images = "fal"
aspect_ratio = "flux_11_ultra"
@@ -83,6 +86,7 @@ outputs = ["image"]
costs = { input = 0.05, output = 0.0 }
[flux-2.rules]
+model_choice = "model_id"
prompt = "positive_only"
num_images = "fal"
aspect_ratio = "flux"
@@ -99,6 +103,7 @@ outputs = ["image"]
costs = { input = 0.0003, output = 0.0 }
[fast-lightning-sdxl.rules]
+model_choice = "model_id"
prompt = "positive_only"
num_images = "fal"
aspect_ratio = "flux"
diff --git a/.pipelex/inference/backends/huggingface.toml b/.pipelex/inference/backends/huggingface.toml
index 2fd0faf8b..b07673cfa 100644
--- a/.pipelex/inference/backends/huggingface.toml
+++ b/.pipelex/inference/backends/huggingface.toml
@@ -39,6 +39,7 @@ variant = "fal-ai"
# variant = "replicate"
[qwen-image.rules]
+model_choice = "model_id"
prompt = "with_negative"
aspect_ratio = "qwen_image"
inference = "qwen_image"
diff --git a/.pipelex/inference/backends/openai.toml b/.pipelex/inference/backends/openai.toml
index c9d9509aa..b75142169 100644
--- a/.pipelex/inference/backends/openai.toml
+++ b/.pipelex/inference/backends/openai.toml
@@ -237,6 +237,14 @@ outputs = ["text", "structured"]
costs = { input = 0.2, output = 1.25 }
thinking_mode = "manual"
+# --- GPT-5.5 Series -----------------------------------------------------------
+["gpt-5.5"]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 5.0, output = 30.0 }
+valued_constraints = { fixed_temperature = 1 }
+thinking_mode = "manual"
+
################################################################################
# IMAGE GENERATION MODELS
################################################################################
@@ -245,21 +253,100 @@ thinking_mode = "manual"
[gpt-image-1]
sdk = "openai_img_gen"
model_type = "img_gen"
-inputs = ["text"]
+inputs = ["text", "images"]
outputs = ["image"]
costs = { input = 10, output = 40 }
+[gpt-image-1.rules]
+model_choice = "model_id"
+prompt = "positive_only"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_legacy"
+background = "available"
+inference = "gpt_image"
+safety_checker = "openai_moderation"
+output_format = "gpt_image_legacy"
+output_compression = "gpt_image_legacy"
+input_images = "gpt_image"
+input_fidelity = "gpt_image_legacy"
+
[gpt-image-1-mini]
sdk = "openai_img_gen"
model_type = "img_gen"
-inputs = ["text"]
+inputs = ["text", "images"]
outputs = ["image"]
costs = { input = 2.5, output = 8 }
+[gpt-image-1-mini.rules]
+model_choice = "model_id"
+prompt = "positive_only"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_legacy"
+background = "available"
+inference = "gpt_image"
+safety_checker = "openai_moderation"
+output_format = "gpt_image_legacy"
+output_compression = "gpt_image_legacy"
+input_images = "gpt_image"
+input_fidelity = "gpt_image_legacy"
+
["gpt-image-1.5"]
sdk = "openai_img_gen"
model_type = "img_gen"
model_id = "gpt-image-1.5"
-inputs = ["text"]
+inputs = ["text", "images"]
outputs = ["image"]
costs = { input = 8, output = 32 }
+
+["gpt-image-1.5".rules]
+model_choice = "model_id"
+prompt = "positive_only"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_legacy"
+background = "available"
+inference = "gpt_image"
+safety_checker = "openai_moderation"
+output_format = "gpt_image_legacy"
+output_compression = "gpt_image_legacy"
+input_images = "gpt_image"
+input_fidelity = "gpt_image_legacy"
+
+[gpt-image-2-2026-04-21]
+sdk = "openai_img_gen"
+model_type = "img_gen"
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 8, output = 30 }
+
+[gpt-image-2-2026-04-21.rules]
+model_choice = "model_id"
+prompt = "positive_only"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_2"
+background = "unavailable"
+inference = "gpt_image"
+safety_checker = "unavailable"
+output_format = "unavailable"
+output_compression = "unavailable"
+input_images = "gpt_image"
+input_fidelity = "unavailable"
+
+[gpt-image-2]
+sdk = "openai_img_gen"
+model_type = "img_gen"
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 8, output = 30 }
+
+[gpt-image-2.rules]
+model_choice = "model_id"
+prompt = "positive_only"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_2"
+background = "unavailable"
+inference = "gpt_image"
+safety_checker = "unavailable"
+output_format = "unavailable"
+output_compression = "unavailable"
+input_images = "gpt_image"
+input_fidelity = "unavailable"
diff --git a/.pipelex/inference/backends/pipelex_gateway_models.md b/.pipelex/inference/backends/pipelex_gateway_models.md
index 52a3d11a0..ddb1b79f8 100644
--- a/.pipelex/inference/backends/pipelex_gateway_models.md
+++ b/.pipelex/inference/backends/pipelex_gateway_models.md
@@ -312,7 +312,7 @@ For configuration details, see the [documentation](https://docs.pipelex.com/late
<td>gpt-5.4</td>
<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
-<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
</tr>
@@ -320,7 +320,7 @@ For configuration details, see the [documentation](https://docs.pipelex.com/late
<td>gpt-5.4-mini</td>
<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
-<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
</tr>
@@ -328,7 +328,7 @@ For configuration details, see the [documentation](https://docs.pipelex.com/late
<td>gpt-5.4-nano</td>
<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
-<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
</tr>
@@ -336,7 +336,15 @@ For configuration details, see the [documentation](https://docs.pipelex.com/late
<td>gpt-5.4-pro</td>
<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
-<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gpt-5.5</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
</tr>
@@ -562,6 +570,12 @@ For configuration details, see the [documentation](https://docs.pipelex.com/late
<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
</tr>
<tr>
+<td>gpt-image-2</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
<td>nano-banana</td>
<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
@@ -584,6 +598,6 @@ For configuration details, see the [documentation](https://docs.pipelex.com/late
> **AUTO-GENERATED FILE** - Do not edit manually.
-> Last updated: 2026-04-17T12:49:19Z
+> Last updated: 2026-04-28T12:50:14Z
>
> Run `pipelex-dev update-gateway-models` or `make ugm` to regenerate.
\ No newline at end of file
diff --git a/.pipelex/inference/backends/pipelex_gateway_models_plain.md b/.pipelex/inference/backends/pipelex_gateway_models_plain.md
index ceeddf916..e39b82f30 100644
--- a/.pipelex/inference/backends/pipelex_gateway_models_plain.md
+++ b/.pipelex/inference/backends/pipelex_gateway_models_plain.md
@@ -116,16 +116,19 @@ For configuration details, see the [documentation](https://docs.pipelex.com/late
- inputs: text, images, pdf
- outputs: text, structured
- **gpt-5.4**
- - inputs: text, images
+ - inputs: text, images, pdf
- outputs: text, structured
- **gpt-5.4-mini**
- - inputs: text, images
+ - inputs: text, images, pdf
- outputs: text, structured
- **gpt-5.4-nano**
- - inputs: text, images
+ - inputs: text, images, pdf
- outputs: text, structured
- **gpt-5.4-pro**
- - inputs: text, images
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gpt-5.5**
+ - inputs: text, images, pdf
- outputs: text, structured
- **gpt-oss-120b**
- inputs: text
@@ -205,6 +208,9 @@ For configuration details, see the [documentation](https://docs.pipelex.com/late
- **gpt-image-1.5**
- inputs: text, images
- outputs: image
+- **gpt-image-2**
+ - inputs: text, images
+ - outputs: image
- **nano-banana**
- inputs: text, images
- outputs: image
@@ -217,6 +223,6 @@ For configuration details, see the [documentation](https://docs.pipelex.com/late
> **AUTO-GENERATED FILE** - Do not edit manually.
-> Last updated: 2026-04-17T12:49:19Z
+> Last updated: 2026-04-28T12:50:14Z
>
> Run `pipelex-dev update-gateway-models` or `make ugm` to regenerate.
\ No newline at end of file
diff --git a/.pipelex/inference/deck/2_img_gen_deck.toml b/.pipelex/inference/deck/2_img_gen_deck.toml
index 3436109f5..33907ae21 100644
--- a/.pipelex/inference/deck/2_img_gen_deck.toml
+++ b/.pipelex/inference/deck/2_img_gen_deck.toml
@@ -26,7 +26,7 @@ choice_default = "$gen-image"
####################################################################################################
[img_gen.aliases]
-best-gpt = "gpt-image-1.5"
+best-gpt = "gpt-image-2"
best-gemini = "nano-banana-2"
default-general = "nano-banana"
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 37e1baf66..f8db7927c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,32 @@
# Changelog
+## [Unreleased]
+
+### Added
+
+- **GPT-5.5 model support.** New `gpt-5.5` entry on the `openai`, `azure_openai` and gateway backends.
+
+- **`gpt-image-2` image generation (OpenAI).** New model entry with img-gen routing and constraints on `openai`, `azure_openai`.
+
+### Fixed
+
+- **PDF input declared on Azure OpenAI and gateway for the GPT-5.4 series.** `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.4-nano`, `gpt-5.4-pro` (and `gpt-5.5`) now advertise `pdf` in their `inputs` on `azure_openai` and the gateway, matching the existing OpenAI direct entries. Verified end-to-end with live document tests against both backends.
+
+### Changed
+
+- **Img-gen taxonomies aligned for `gpt-image-2`.** Convention: `gpt_image` for taxonomies/values shared across all OpenAI GPT Image models (legacy + gpt-image-2); `gpt_image_legacy` when the value applies only to gpt-image-1/-1-mini/-1.5 (gpt-image-2 uses `unavailable` where a legacy-only option does not apply). Renames:
+ - `AspectRatioTaxonomy.OPENAI_GPT_IMAGE_LEGACY` → `GPT_IMAGE_LEGACY` (value `"openai_gpt_image_legacy"` → `"gpt_image_legacy"`)
+ - `AspectRatioTaxonomy.OPENAI_GPT_IMAGE_2` → `GPT_IMAGE_2` (value `"openai_gpt_image_2"` → `"gpt_image_2"`)
+ - `OutputFormatTaxonomy.GPT` → `GPT_IMAGE_LEGACY` (value `"gpt"` → `"gpt_image_legacy"`)
+ - `OutputCompressionTaxonomy.GPT_IMAGE` → `GPT_IMAGE_LEGACY` (value `"gpt_image"` → `"gpt_image_legacy"`)
+ - `InputFidelityTaxonomy.OPENAI_IMAGE` → `GPT_IMAGE_LEGACY` (value `"openai_image"` → `"gpt_image_legacy"`)
+ - `NumImagesTaxonomy.GPT` → `GPT_IMAGE` (value `"gpt"` → `"gpt_image"`)
+ - `InferenceTaxonomy.GPT` → `GPT_IMAGE` (value `"gpt"` → `"gpt_image"`)
+ - Removed dead `AspectRatioTaxonomy.GPT`.
+ - `InputImagesTaxonomy.GPT_IMAGE` unchanged (already correct — shared across legacy and gpt-image-2).
+
+- **HuggingFace and Fal img-gen workers honor `model_choice` rule.** `huggingface_img_gen` and `fal` workers now pop `"model"` from `args_dict` instead of hardcoding `inference_model.model_id`, mirroring how `prompt` is already extracted. The `model_choice = "model_id"` rule is now required on every model under these backends; missing it raises `ImgGenParameterError` at call time. Rules added to `qwen-image` (HF) and to all Fal models (`flux-pro`, `flux-pro/v1.1`, `flux-pro/v1.1-ultra`, `flux-2`, `fast-lightning-sdxl`).
+
## [v0.24.1] - 2026-04-22
### Security
diff --git a/TODOS.md b/TODOS.md
deleted file mode 100644
index 3ec03b87b..000000000
--- a/TODOS.md
+++ /dev/null
@@ -1,17 +0,0 @@
-# TODOs
-
-## Graph viewer: use relative URLs for storage assets
-
-**What:** When generating graph HTML output, copy referenced storage files (images, PDFs) into an `assets/` subdirectory next to the HTML file and set `public_url` to relative paths (`assets/filename.ext`) instead of `file://` absolute paths.
-
-**Why:** `file://` URLs are blocked by browsers when the HTML is served over HTTP (e.g., `localhost:3002`). Images and PDFs don't render in the graph viewer panel. Relative URLs work in all contexts: opened as a local file, served over HTTP, zipped and shared, or deployed to cloud.
-
-**Where to start:**
-- `pipelex/tools/storage/local_storage_provider.py:108-119` — where `file://` URLs are generated via `file_path.as_uri()`
-- `pipelex/graph/graph_rendering.py` — where graph HTML is generated. This is where file copying should happen.
-- `pipelex/pipeline/input_normalizer.py:182-239` — where `public_url` is populated on ImageContent/DocumentContent
-- S3/GCP providers already generate absolute HTTPS URLs and need no changes
-
-**Approach:** During graph HTML generation, resolve all `pipelex-storage://` URIs to local file paths, copy them into an `assets/` subdirectory next to the output HTML, and rewrite `public_url` to the relative path. This follows the pattern used by pytest-html, Allure reports, and static site generators.
-
-**Depends on:** Nothing. Self-contained change in pipelex.
diff --git a/pipelex/cogt/img_gen/img_gen_args_factory.py b/pipelex/cogt/img_gen/img_gen_args_factory.py
index 68695ba6f..7426e9828 100644
--- a/pipelex/cogt/img_gen/img_gen_args_factory.py
+++ b/pipelex/cogt/img_gen/img_gen_args_factory.py
@@ -11,19 +11,22 @@ from typing import Any
from pipelex import log
from pipelex.cogt.exceptions import ImgGenParameterError
+from pipelex.cogt.image.image_size import ImageSize
from pipelex.cogt.image.prompt_image import PromptImage
from pipelex.cogt.image.prompt_image_utils import prep_prompt_images
from pipelex.cogt.img_gen.img_gen_job import ImgGenJob
-from pipelex.cogt.img_gen.img_gen_job_components import AspectRatio, Background, Quality
+from pipelex.cogt.img_gen.img_gen_job_components import AspectRatio, Background, InputFidelity, Quality
from pipelex.cogt.img_gen.img_gen_model_rules import (
AspectRatioTaxonomy,
BackgroundTaxonomy,
ImgGenArgTopic,
ImgGenModelRules,
InferenceTaxonomy,
+ InputFidelityTaxonomy,
InputImagesTaxonomy,
- ModelNameTaxonomy,
+ ModelChoiceTaxonomy,
NumImagesTaxonomy,
+ OutputCompressionTaxonomy,
OutputFormatTaxonomy,
PromptTaxonomy,
SafetyCheckerTaxonomy,
@@ -49,6 +52,7 @@ class ImgGenArgsFactory:
img_gen_job: ImgGenJob,
nb_images: int,
model_id: str,
+ model_name: str,
) -> dict[str, Any]:
"""Build provider-specific API arguments from model rules and job parameters.
@@ -59,7 +63,8 @@ class ImgGenArgsFactory:
model_rules: Mapping of argument topics to their taxonomy values for the target model
img_gen_job: The image generation job containing prompt and parameters
nb_images: Number of images to generate
- model_id: The model identifier to pass to the provider API
+ model_id: The model identifier
+ model_name: The config model name
Returns:
Dictionary of API arguments ready to be passed to the provider's API
@@ -93,6 +98,8 @@ class ImgGenArgsFactory:
cls.make_args_from_aspect_ratio(
aspect_ratio_taxonomy=aspect_ratio_taxonomy,
aspect_ratio=job_params.aspect_ratio,
+ size=job_params.size,
+ model_name=model_name,
)
)
case ImgGenArgTopic.BACKGROUND:
@@ -101,6 +108,7 @@ class ImgGenArgsFactory:
cls.make_args_from_background(
background_taxonomy=background_taxonomy,
background=job_params.background,
+ model_name=model_name,
)
)
case ImgGenArgTopic.INFERENCE:
@@ -125,11 +133,17 @@ class ImgGenArgsFactory:
)
case ImgGenArgTopic.OUTPUT_FORMAT:
output_format_taxonomy = OutputFormatTaxonomy(taxonomy_value)
- # TODO: test without imposing the format
args_dict.update(
cls.make_args_from_output_format(
output_format_taxonomy=output_format_taxonomy,
- output_format=job_params.output_format or ImageFormat.PNG,
+ output_format=job_params.output_format,
+ )
+ )
+ case ImgGenArgTopic.OUTPUT_COMPRESSION:
+ output_compression_taxonomy = OutputCompressionTaxonomy(taxonomy_value)
+ args_dict.update(
+ cls.make_args_from_output_compression(
+ output_compression_taxonomy=output_compression_taxonomy,
)
)
case ImgGenArgTopic.SPECIFIC:
@@ -139,12 +153,13 @@ class ImgGenArgsFactory:
specific_taxonomy=specific_taxonomy,
)
)
- case ImgGenArgTopic.MODEL_NAME:
- model_name_taxonomy = ModelNameTaxonomy(taxonomy_value)
+ case ImgGenArgTopic.MODEL_CHOICE:
+ model_name_taxonomy = ModelChoiceTaxonomy(taxonomy_value)
args_dict.update(
cls.make_args_from_model_name(
model_name_taxonomy=model_name_taxonomy,
model_id=model_id,
+ model_name=model_name,
)
)
case ImgGenArgTopic.INPUT_IMAGES:
@@ -154,6 +169,15 @@ class ImgGenArgsFactory:
input_images=img_gen_job.img_gen_prompt.input_images,
)
args_dict.update(input_images_args)
+ case ImgGenArgTopic.INPUT_FIDELITY:
+ input_fidelity_taxonomy = InputFidelityTaxonomy(taxonomy_value)
+ args_dict.update(
+ cls.make_args_from_input_fidelity(
+ input_fidelity_taxonomy=input_fidelity_taxonomy,
+ input_fidelity=job_params.input_fidelity,
+ model_name=model_name,
+ )
+ )
# Validate that input_images were processed if provided
if img_gen_job.img_gen_prompt.input_images:
@@ -164,6 +188,10 @@ class ImgGenArgsFactory:
)
raise ImgGenParameterError(msg)
+ if job_params.input_fidelity is not None and ImgGenArgTopic.INPUT_FIDELITY not in model_rules:
+ msg = f"Model '{model_id}' does not support input_fidelity"
+ raise ImgGenParameterError(msg)
+
return args_dict
@classmethod
@@ -172,7 +200,7 @@ class ImgGenArgsFactory:
match num_images_taxonomy:
case NumImagesTaxonomy.FAL:
return {"num_images": nb_images}
- case NumImagesTaxonomy.GPT:
+ case NumImagesTaxonomy.GPT_IMAGE:
return {"n": nb_images}
@classmethod
@@ -207,23 +235,42 @@ class ImgGenArgsFactory:
@classmethod
def make_args_from_model_name(
cls,
- model_name_taxonomy: ModelNameTaxonomy,
+ model_name_taxonomy: ModelChoiceTaxonomy,
model_id: str,
+ model_name: str,
) -> dict[str, Any]:
"""Map model identifier to provider-specific parameter."""
match model_name_taxonomy:
- case ModelNameTaxonomy.STANDARD:
+ case ModelChoiceTaxonomy.MODEL_ID:
return {"model": model_id}
+ case ModelChoiceTaxonomy.MODEL_NAME:
+ return {"model": model_name}
@classmethod
- def make_args_from_background(cls, background_taxonomy: BackgroundTaxonomy, background: Background) -> dict[str, Any]:
- """Map background setting to provider-specific parameter."""
+ def make_args_from_background(cls, background_taxonomy: BackgroundTaxonomy, background: Background, model_name: str) -> dict[str, Any]:
+ """Map background setting to provider-specific parameter.
+
+ Raises:
+ ImgGenParameterError: If the model does not support background configuration
+ (taxonomy is UNAVAILABLE) and a transparent background was requested.
+ """
match background_taxonomy:
- case BackgroundTaxonomy.GPT:
+ case BackgroundTaxonomy.AVAILABLE:
return {"background": background.value}
+ case BackgroundTaxonomy.UNAVAILABLE:
+ if background.is_certainly_transparent:
+ msg = f"Model '{model_name}' does not support transparent background"
+ raise ImgGenParameterError(msg)
+ return {}
@classmethod
- def make_args_from_aspect_ratio(cls, aspect_ratio_taxonomy: AspectRatioTaxonomy, aspect_ratio: AspectRatio) -> dict[str, Any]:
+ def make_args_from_aspect_ratio(
+ cls,
+ aspect_ratio_taxonomy: AspectRatioTaxonomy,
+ aspect_ratio: AspectRatio,
+ size: ImageSize | None,
+ model_name: str,
+ ) -> dict[str, Any]:
"""Map aspect ratio to provider-specific parameter name and value format.
Raises:
@@ -272,9 +319,20 @@ class ImgGenArgsFactory:
case AspectRatio.LANDSCAPE_3_2 | AspectRatio.PORTRAIT_2_3:
msg = f"Aspect ratio '{aspect_ratio}' is not supported by Flux-1.1 Ultra image generation model"
raise ImgGenParameterError(msg)
- case AspectRatioTaxonomy.GPT:
+ case AspectRatioTaxonomy.GPT_IMAGE_LEGACY:
+ key = "size"
+ value = OpenAIImgGenFactory.size_for_legacy_openai_image(
+ model_name=model_name,
+ aspect_ratio=aspect_ratio,
+ size=size,
+ )[0]
+ case AspectRatioTaxonomy.GPT_IMAGE_2:
key = "size"
- value = OpenAIImgGenFactory.image_size_for_gpt_image_1(aspect_ratio)[0]
+ value = OpenAIImgGenFactory.size_for_gpt_image_2(
+ model_name=model_name,
+ aspect_ratio=aspect_ratio,
+ size=size,
+ )[0]
case AspectRatioTaxonomy.QWEN_IMAGE:
width: int
height: int
@@ -354,9 +412,8 @@ class ImgGenArgsFactory:
case InferenceTaxonomy.FLUX_11_ULTRA:
if is_raw:
args_dict["raw"] = is_raw
- case InferenceTaxonomy.GPT:
- if quality:
- args_dict["quality"] = quality.value
+ case InferenceTaxonomy.GPT_IMAGE:
+ args_dict["quality"] = (quality or Quality.MEDIUM).value
return args_dict
@classmethod
@@ -375,6 +432,11 @@ class ImgGenArgsFactory:
match safety_checker_taxonomy:
case SafetyCheckerTaxonomy.UNAVAILABLE:
pass
+ case SafetyCheckerTaxonomy.OPENAI_MODERATION:
+ moderation = OpenAIImgGenFactory.moderation_for_openai_image(is_moderated=is_moderated)
+ if not isinstance(moderation, str):
+ return args_dict
+ args_dict["moderation"] = moderation
case SafetyCheckerTaxonomy.AVAILABLE:
if is_moderated is not None:
args_dict["enable_safety_checker"] = is_moderated
@@ -386,10 +448,12 @@ class ImgGenArgsFactory:
def make_args_from_output_format(
cls,
output_format_taxonomy: OutputFormatTaxonomy,
- output_format: ImageFormat,
+ output_format: ImageFormat | None,
) -> dict[str, Any]:
"""Map output format to provider-specific parameter name and validate support.
+ When output_format is None, returns an empty dict so the provider applies its own default.
+
Raises:
ImgGenParameterError: If the output format is not supported by the target model
"""
@@ -397,6 +461,8 @@ class ImgGenArgsFactory:
value: str
match output_format_taxonomy:
case OutputFormatTaxonomy.SDXL:
+ if output_format is None:
+ return {}
key = "format"
match output_format:
case ImageFormat.PNG:
@@ -407,6 +473,8 @@ class ImgGenArgsFactory:
msg = "Output format WebP is not supported by SDXL image generation models"
raise ImgGenParameterError(msg)
case OutputFormatTaxonomy.FLUX_1:
+ if output_format is None:
+ return {}
key = "output_format"
match output_format:
case ImageFormat.PNG:
@@ -417,13 +485,35 @@ class ImgGenArgsFactory:
msg = "Output format WebP is not supported by Flux 1 image generation models"
raise ImgGenParameterError(msg)
case OutputFormatTaxonomy.FLUX_2:
+ if output_format is None:
+ return {}
key = "output_format"
value = output_format.value
- case OutputFormatTaxonomy.GPT:
+ case OutputFormatTaxonomy.GPT_IMAGE_LEGACY:
+ if output_format is None:
+ return {}
key = "output_format"
value = output_format.value
+ case OutputFormatTaxonomy.UNAVAILABLE:
+ return {}
return {key: value}
+ @classmethod
+ def make_args_from_output_compression(
+ cls,
+ output_compression_taxonomy: OutputCompressionTaxonomy,
+ ) -> dict[str, Any]:
+ """Map output compression to provider-specific parameter.
+
+ OpenAI gpt-image-1/-1-mini/-1.5 accept `output_compression` (0-100) for JPEG/WEBP outputs.
+ PNG ignores this value (lossless). Models that do not expose this parameter use UNAVAILABLE.
+ """
+ match output_compression_taxonomy:
+ case OutputCompressionTaxonomy.GPT_IMAGE_LEGACY:
+ return {"output_compression": 100}
+ case OutputCompressionTaxonomy.UNAVAILABLE:
+ return {}
+
@classmethod
async def make_args_from_input_images(
cls,
@@ -481,3 +571,23 @@ class ImgGenArgsFactory:
msg = f"Unexpected PreparedFile type for Flux 2 API: {type(prepped).__name__}"
raise ImgGenParameterError(msg)
return args
+
+ @classmethod
+ def make_args_from_input_fidelity(
+ cls,
+ input_fidelity_taxonomy: InputFidelityTaxonomy,
+ input_fidelity: InputFidelity | None,
+ model_name: str,
+ ) -> dict[str, Any]:
+ """Map input fidelity settings for image editing."""
+ if input_fidelity is None:
+ return {}
+
+ match input_fidelity_taxonomy:
+ case InputFidelityTaxonomy.GPT_IMAGE_LEGACY:
+ return {
+ "input_fidelity": OpenAIImgGenFactory.input_fidelity_for_openai_image(input_fidelity=input_fidelity),
+ }
+ case InputFidelityTaxonomy.UNAVAILABLE:
+ msg = f"Model '{model_name}' does not support input_fidelity"
+ raise ImgGenParameterError(msg)
diff --git a/pipelex/cogt/img_gen/img_gen_job_components.py b/pipelex/cogt/img_gen/img_gen_job_components.py
index 255834a24..43e168a98 100644
--- a/pipelex/cogt/img_gen/img_gen_job_components.py
+++ b/pipelex/cogt/img_gen/img_gen_job_components.py
@@ -2,6 +2,7 @@ from typing import Literal
from pydantic import BaseModel, Field, model_validator
+from pipelex.cogt.image.image_size import ImageSize
from pipelex.cogt.img_gen.img_gen_report import ImgGenTokensUsage
from pipelex.system.configuration.config_model import ConfigModel
from pipelex.tools.misc.image_utils import ImageFormat
@@ -26,6 +27,11 @@ class Quality(StrEnum):
HIGH = "high"
+class InputFidelity(StrEnum):
+ LOW = "low"
+ HIGH = "high"
+
+
class Background(StrEnum):
TRANSPARENT = "transparent"
OPAQUE = "opaque"
@@ -42,8 +48,10 @@ class Background(StrEnum):
class ImgGenJobParams(BaseModel):
aspect_ratio: AspectRatio = Field(strict=False)
+ size: ImageSize | None = None
background: Background = Field(strict=False)
quality: Quality | None = Field(default=None, strict=False)
+ input_fidelity: InputFidelity | None = Field(default=None, strict=False)
nb_steps: int | None = Field(default=None, gt=0)
guidance_scale: float | None = Field(default=None, gt=0)
is_moderated: bool | None = None
diff --git a/pipelex/cogt/img_gen/img_gen_model_rules.py b/pipelex/cogt/img_gen/img_gen_model_rules.py
index 72ff17553..b174e988e 100644
--- a/pipelex/cogt/img_gen/img_gen_model_rules.py
+++ b/pipelex/cogt/img_gen/img_gen_model_rules.py
@@ -22,7 +22,7 @@ class ImgGenArgTopic(StrEnum):
depending on the model backend being used.
"""
- MODEL_NAME = "model_name"
+ MODEL_CHOICE = "model_choice"
PROMPT = "prompt"
NUM_IMAGES = "num_images"
ASPECT_RATIO = "aspect_ratio"
@@ -30,8 +30,10 @@ class ImgGenArgTopic(StrEnum):
SAFETY_CHECKER = "safety_checker"
BACKGROUND = "background"
OUTPUT_FORMAT = "output_format"
+ OUTPUT_COMPRESSION = "output_compression"
SPECIFIC = "specific"
INPUT_IMAGES = "input_images"
+ INPUT_FIDELITY = "input_fidelity"
class NumImagesTaxonomy(StrEnum):
@@ -39,11 +41,11 @@ class NumImagesTaxonomy(StrEnum):
Different providers use different parameter names:
- FAL: uses `num_images`
- - GPT: uses `n`
+ - GPT_IMAGE: uses `n` (shared across all OpenAI GPT Image models — legacy and gpt-image-2)
"""
FAL = "fal"
- GPT = "gpt"
+ GPT_IMAGE = "gpt_image"
class SpecificTaxonomy(StrEnum):
@@ -73,7 +75,8 @@ class AspectRatioTaxonomy(StrEnum):
Different providers use different parameter names and value formats:
- FLUX: uses `image_size` with values like "square_hd", "landscape_4_3"
- FLUX_11_ULTRA: uses `aspect_ratio` with values like "1:1", "4:3"
- - GPT: uses `size` with pixel dimensions like "1024x1024"
+ - GPT_IMAGE_LEGACY: uses fixed OpenAI GPT Image sizes (gpt-image-1 / -1-mini / -1.5)
+ - GPT_IMAGE_2: validates and forwards exact OpenAI GPT Image 2 sizes
- QWEN_IMAGE: uses `width` and `height` with pixel dimensions mapped from aspect ratios
(e.g., "1:1" -> 1328x1328, "16:9" -> 1664x928, "9:16" -> 928x1664,
"4:3" -> 1472x1140, "3:4" -> 1140x1472, "3:2" -> 1584x1056, "2:3" -> 1056x1584)
@@ -81,7 +84,8 @@ class AspectRatioTaxonomy(StrEnum):
FLUX = "flux"
FLUX_11_ULTRA = "flux_11_ultra"
- GPT = "gpt"
+ GPT_IMAGE_LEGACY = "gpt_image_legacy"
+ GPT_IMAGE_2 = "gpt_image_2"
QWEN_IMAGE = "qwen_image"
@@ -92,14 +96,14 @@ class InferenceTaxonomy(StrEnum):
- SDXL_LIGHTNING: uses `num_inference_steps` (valid: 1, 2, 4, 8)
- FLUX: uses `num_inference_steps` and `guidance_scale`
- FLUX_11_ULTRA: uses `raw` mode
- - GPT: uses `quality` ("low", "medium", "high")
+ - GPT_IMAGE: uses `quality` ("low", "medium", "high") — shared across all OpenAI GPT Image models
- QWEN_IMAGE: uses `num_inference_steps` and `guidance_scale`
"""
SDXL_LIGHTNING = "sdxl_lightning"
FLUX = "flux"
FLUX_11_ULTRA = "flux_11_ultra"
- GPT = "gpt"
+ GPT_IMAGE = "gpt_image"
QWEN_IMAGE = "qwen_image"
@@ -107,20 +111,25 @@ class SafetyCheckerTaxonomy(StrEnum):
"""Taxonomy for safety checker availability.
- AVAILABLE: model supports `enable_safety_checker` and `safety_tolerance` parameters
+ - OPENAI_MODERATION: model supports OpenAI `moderation` parameter
- UNAVAILABLE: model does not expose safety checker configuration
"""
AVAILABLE = "available"
+ OPENAI_MODERATION = "openai_moderation"
UNAVAILABLE = "unavailable"
class BackgroundTaxonomy(StrEnum):
"""Taxonomy for background transparency/removal parameters.
- - GPT: supports `background` parameter for transparency control
+ - AVAILABLE: supports `background` parameter for transparency control
+ - UNAVAILABLE: model does not support setting background; the parameter is skipped
+ and requesting a transparent background raises ImgGenParameterError
"""
- GPT = "gpt"
+ AVAILABLE = "available"
+ UNAVAILABLE = "unavailable"
class OutputFormatTaxonomy(StrEnum):
@@ -130,22 +139,39 @@ class OutputFormatTaxonomy(StrEnum):
- SDXL: uses `format`, supports png/jpeg only
- FLUX_1: uses `output_format`, supports png/jpeg only
- FLUX_2: uses `output_format`, supports png/jpeg/webp
- - GPT: uses `output_format`, supports png/jpeg/webp
+ - GPT_IMAGE_LEGACY: uses `output_format`, supports png/jpeg/webp (gpt-image-1 / -1-mini / -1.5).
+ gpt-image-2 ignores `output_format` and uses `OutputFormatTaxonomy.UNAVAILABLE` instead.
"""
SDXL = "sdxl"
FLUX_1 = "flux_1"
FLUX_2 = "flux_2"
- GPT = "gpt"
+ GPT_IMAGE_LEGACY = "gpt_image_legacy"
+ UNAVAILABLE = "unavailable"
-class ModelNameTaxonomy(StrEnum):
- """Taxonomy for how model name/id is passed to the API.
+class OutputCompressionTaxonomy(StrEnum):
+ """Taxonomy for output compression parameters.
- - STANDARD: passes model as {"model": model_id}
+ - GPT_IMAGE_LEGACY: emits `output_compression = 100` for OpenAI gpt-image-1/-1-mini/-1.5
+ (lossless for PNG, max quality for JPEG/WEBP). gpt-image-2 does not expose this param
+ and uses `UNAVAILABLE` instead — hence the `_legacy` suffix.
+ - UNAVAILABLE: model does not expose `output_compression`; the parameter is skipped
"""
- STANDARD = "standard"
+ GPT_IMAGE_LEGACY = "gpt_image_legacy"
+ UNAVAILABLE = "unavailable"
+
+
+class ModelChoiceTaxonomy(StrEnum):
+ """Taxonomy for how model choice is passed to the API.
+
+ - MODEL_ID: passes model as {"model": model_id}
+ - MODEL_NAME: passes model as {"model": model_name}
+ """
+
+ MODEL_ID = "model_id"
+ MODEL_NAME = "model_name"
class InputImagesTaxonomy(StrEnum):
@@ -162,4 +188,17 @@ class InputImagesTaxonomy(StrEnum):
NONE = "none"
+class InputFidelityTaxonomy(StrEnum):
+ """Taxonomy for image-editing fidelity controls.
+
+ - GPT_IMAGE_LEGACY: OpenAI GPT Image edit `input_fidelity`, values "low" or "high"
+ (gpt-image-1/-1-mini/-1.5). gpt-image-2 does not expose this param and uses
+ `UNAVAILABLE` instead — hence the `_legacy` suffix.
+ - UNAVAILABLE: model does not support input fidelity configuration
+ """
+
+ GPT_IMAGE_LEGACY = "gpt_image_legacy"
+ UNAVAILABLE = "unavailable"
+
+
ImgGenModelRules = dict[ImgGenArgTopic, str]
diff --git a/pipelex/cogt/img_gen/img_gen_param_support.py b/pipelex/cogt/img_gen/img_gen_param_support.py
new file mode 100644
index 000000000..957ad025a
--- /dev/null
+++ b/pipelex/cogt/img_gen/img_gen_param_support.py
@@ -0,0 +1,223 @@
+"""Capability checks for img-gen parameter values against a model's rules.
+
+These helpers tell you whether a value would be accepted by a given model's
+rules, without actually building API arguments. They reuse `ImgGenArgsFactory`
+as the single source of truth: each check internally calls the corresponding
+`make_args_from_*` and captures `ImgGenParameterError`.
+
+Used by:
+- Tests, to gracefully `pytest.skip` when a model can't honor a parametrized value.
+- `PipeImgGen` blueprint validation, to surface config errors at load time.
+
+Unknown-taxonomy policy: if a rule value cannot be parsed into the expected
+taxonomy enum, the check abstains (returns supported=True). Some backends
+(e.g. the Pipelex gateway) carry rules whose taxonomy strings predate this
+factory, and those rules are consumed by a different worker — abstaining
+prevents false negatives in those cases.
+"""
+
+from typing import NamedTuple
+
+from pipelex import log
+from pipelex.cogt.exceptions import ImgGenParameterError
+from pipelex.cogt.image.image_size import ImageSize
+from pipelex.cogt.img_gen.img_gen_args_factory import ImgGenArgsFactory
+from pipelex.cogt.img_gen.img_gen_job_components import AspectRatio, Background, ImgGenJobParams, InputFidelity
+from pipelex.cogt.img_gen.img_gen_model_rules import (
+ AspectRatioTaxonomy,
+ BackgroundTaxonomy,
+ ImgGenArgTopic,
+ ImgGenModelRules,
+ InputFidelityTaxonomy,
+ OutputFormatTaxonomy,
+)
+from pipelex.tools.misc.image_utils import ImageFormat
+
+
+class SupportCheck(NamedTuple):
+ """Result of a single parameter-support check.
+
+ `reason` is populated only when `is_supported` is False.
+ """
+
+ is_supported: bool
+ reason: str | None
+
+
+_SUPPORTED = SupportCheck(is_supported=True, reason=None)
+
+
+class ImgGenParamSupport:
+ """Yes/no support checks against ImgGenModelRules for each topic.
+
+ Each check returns a SupportCheck rather than raising. The aggregate methods
+ (check_job_params, check_blueprint_params) return a list of unsupported
+ reasons (empty if all good).
+ """
+
+ @classmethod
+ def check_aspect_ratio(
+ cls,
+ rules: ImgGenModelRules,
+ aspect_ratio: AspectRatio,
+ size: ImageSize | None,
+ model_name: str,
+ ) -> SupportCheck:
+ taxonomy_value = rules.get(ImgGenArgTopic.ASPECT_RATIO)
+ if taxonomy_value is None:
+ return _SUPPORTED
+ try:
+ taxonomy = AspectRatioTaxonomy(taxonomy_value)
+ except ValueError:
+ log.debug(f"Abstaining: unknown AspectRatioTaxonomy '{taxonomy_value}' for model '{model_name}'")
+ return _SUPPORTED
+ try:
+ ImgGenArgsFactory.make_args_from_aspect_ratio(
+ aspect_ratio_taxonomy=taxonomy,
+ aspect_ratio=aspect_ratio,
+ size=size,
+ model_name=model_name,
+ )
+ except ImgGenParameterError as exc:
+ return SupportCheck(is_supported=False, reason=str(exc))
+ return _SUPPORTED
+
+ @classmethod
+ def check_background(
+ cls,
+ rules: ImgGenModelRules,
+ background: Background,
+ model_name: str,
+ ) -> SupportCheck:
+ taxonomy_value = rules.get(ImgGenArgTopic.BACKGROUND)
+ if taxonomy_value is None:
+ return _SUPPORTED
+ try:
+ taxonomy = BackgroundTaxonomy(taxonomy_value)
+ except ValueError:
+ log.debug(f"Abstaining: unknown BackgroundTaxonomy '{taxonomy_value}' for model '{model_name}'")
+ return _SUPPORTED
+ try:
+ ImgGenArgsFactory.make_args_from_background(
+ background_taxonomy=taxonomy,
+ background=background,
+ model_name=model_name,
+ )
+ except ImgGenParameterError as exc:
+ return SupportCheck(is_supported=False, reason=str(exc))
+ return _SUPPORTED
+
+ @classmethod
+ def check_output_format(
+ cls,
+ rules: ImgGenModelRules,
+ output_format: ImageFormat | None,
+ ) -> SupportCheck:
+ taxonomy_value = rules.get(ImgGenArgTopic.OUTPUT_FORMAT)
+ if taxonomy_value is None:
+ return _SUPPORTED
+ try:
+ taxonomy = OutputFormatTaxonomy(taxonomy_value)
+ except ValueError:
+ log.debug(f"Abstaining: unknown OutputFormatTaxonomy '{taxonomy_value}'")
+ return _SUPPORTED
+ try:
+ ImgGenArgsFactory.make_args_from_output_format(
+ output_format_taxonomy=taxonomy,
+ output_format=output_format,
+ )
+ except ImgGenParameterError as exc:
+ return SupportCheck(is_supported=False, reason=str(exc))
+ return _SUPPORTED
+
+ @classmethod
+ def check_input_fidelity(
+ cls,
+ rules: ImgGenModelRules,
+ input_fidelity: InputFidelity | None,
+ model_name: str,
+ ) -> SupportCheck:
+ taxonomy_value = rules.get(ImgGenArgTopic.INPUT_FIDELITY)
+ if taxonomy_value is None:
+ if input_fidelity is None:
+ return _SUPPORTED
+ reason = f"Model '{model_name}' does not support input_fidelity"
+ return SupportCheck(is_supported=False, reason=reason)
+ try:
+ taxonomy = InputFidelityTaxonomy(taxonomy_value)
+ except ValueError:
+ log.debug(f"Abstaining: unknown InputFidelityTaxonomy '{taxonomy_value}' for model '{model_name}'")
+ return _SUPPORTED
+ try:
+ ImgGenArgsFactory.make_args_from_input_fidelity(
+ input_fidelity_taxonomy=taxonomy,
+ input_fidelity=input_fidelity,
+ model_name=model_name,
+ )
+ except ImgGenParameterError as exc:
+ return SupportCheck(is_supported=False, reason=str(exc))
+ return _SUPPORTED
+
+ @classmethod
+ def check_input_images_topic(
+ cls,
+ rules: ImgGenModelRules,
+ has_input_images: bool,
+ ) -> SupportCheck:
+ if not has_input_images:
+ return _SUPPORTED
+ if ImgGenArgTopic.INPUT_IMAGES in rules:
+ return _SUPPORTED
+ reason = (
+ "Input images were provided but the model does not have 'input_images' rules configured. "
+ "This model may not support image-to-image generation."
+ )
+ return SupportCheck(is_supported=False, reason=reason)
+
+ @classmethod
+ def check_job_params(
+ cls,
+ rules: ImgGenModelRules,
+ params: ImgGenJobParams,
+ model_name: str,
+ has_input_images: bool = False,
+ ) -> list[str]:
+ """Run all relevant checks; return list of unsupported reasons (empty if all good)."""
+ checks: list[SupportCheck] = [
+ cls.check_aspect_ratio(rules=rules, aspect_ratio=params.aspect_ratio, size=params.size, model_name=model_name),
+ cls.check_background(rules=rules, background=params.background, model_name=model_name),
+ cls.check_output_format(rules=rules, output_format=params.output_format),
+ cls.check_input_fidelity(rules=rules, input_fidelity=params.input_fidelity, model_name=model_name),
+ cls.check_input_images_topic(rules=rules, has_input_images=has_input_images),
+ ]
+ return [check.reason for check in checks if not check.is_supported and check.reason is not None]
+
+ @classmethod
+ def check_blueprint_params(
+ cls,
+ rules: ImgGenModelRules,
+ *,
+ aspect_ratio: AspectRatio | None,
+ background: Background | None,
+ output_format: ImageFormat | None,
+ model_name: str,
+ ) -> list[str]:
+ """Check blueprint fields that are explicitly set.
+
+ None means "deck default applies later" — those are NOT checked, since the
+ actual value is unknown at blueprint load time.
+ """
+ reasons: list[str] = []
+ if aspect_ratio is not None:
+ check = cls.check_aspect_ratio(rules=rules, aspect_ratio=aspect_ratio, size=None, model_name=model_name)
+ if not check.is_supported and check.reason is not None:
+ reasons.append(check.reason)
+ if background is not None:
+ check = cls.check_background(rules=rules, background=background, model_name=model_name)
+ if not check.is_supported and check.reason is not None:
+ reasons.append(check.reason)
+ if output_format is not None:
+ check = cls.check_output_format(rules=rules, output_format=output_format)
+ if not check.is_supported and check.reason is not None:
+ reasons.append(check.reason)
+ return reasons
diff --git a/pipelex/kit/configs/inference/backends/azure_openai.toml b/pipelex/kit/configs/inference/backends/azure_openai.toml
index 49918a036..b1b7e7aa8 100644
--- a/pipelex/kit/configs/inference/backends/azure_openai.toml
+++ b/pipelex/kit/configs/inference/backends/azure_openai.toml
@@ -190,14 +190,14 @@ thinking_mode = "manual"
# --- GPT-5.4 Series -----------------------------------------------------------
["gpt-5.4"]
model_id = "gpt-5.4-2026-03-05"
-inputs = ["text", "images"]
+inputs = ["text", "images", "pdf"]
outputs = ["text", "structured"]
costs = { input = 2.5, output = 15.0 }
thinking_mode = "manual"
["gpt-5.4-pro"]
model_id = "gpt-5.4-pro-2026-03-05"
-inputs = ["text", "images"]
+inputs = ["text", "images", "pdf"]
outputs = ["text", "structured"]
costs = { input = 30.0, output = 180.0 }
valued_constraints = { fixed_temperature = 1 }
@@ -205,18 +205,27 @@ thinking_mode = "manual"
["gpt-5.4-mini"]
model_id = "gpt-5.4-mini-2026-03-17"
-inputs = ["text", "images"]
+inputs = ["text", "images", "pdf"]
outputs = ["text", "structured"]
costs = { input = 0.75, output = 4.5 }
thinking_mode = "manual"
["gpt-5.4-nano"]
model_id = "gpt-5.4-nano-2026-03-17"
-inputs = ["text", "images"]
+inputs = ["text", "images", "pdf"]
outputs = ["text", "structured"]
costs = { input = 0.2, output = 1.25 }
thinking_mode = "manual"
+# --- GPT-5.5 Series -----------------------------------------------------------
+["gpt-5.5"]
+model_id = "gpt-5.5-2026-04-24"
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 5.0, output = 30.0 }
+valued_constraints = { fixed_temperature = 1 }
+thinking_mode = "manual"
+
################################################################################
# IMAGE GENERATION MODELS
################################################################################
@@ -232,12 +241,14 @@ costs = { input = 10, output = 40 }
[gpt-image-1.rules]
prompt = "positive_only"
-num_images = "gpt"
-aspect_ratio = "gpt"
-background = "gpt"
-inference = "gpt"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_legacy"
+background = "available"
+inference = "gpt_image"
safety_checker = "unavailable"
-output_format = "gpt"
+output_format = "gpt_image_legacy"
+output_compression = "gpt_image_legacy"
+input_fidelity = "gpt_image_legacy"
[gpt-image-1-mini]
sdk = "azure_rest_img_gen"
@@ -249,12 +260,14 @@ costs = { input = 2.5, output = 8 }
[gpt-image-1-mini.rules]
prompt = "positive_only"
-num_images = "gpt"
-aspect_ratio = "gpt"
-background = "gpt"
-inference = "gpt"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_legacy"
+background = "available"
+inference = "gpt_image"
safety_checker = "unavailable"
-output_format = "gpt"
+output_format = "gpt_image_legacy"
+output_compression = "gpt_image_legacy"
+input_fidelity = "gpt_image_legacy"
["gpt-image-1.5"]
sdk = "azure_rest_img_gen"
@@ -266,9 +279,30 @@ costs = { input = 8, output = 32 }
["gpt-image-1.5".rules]
prompt = "positive_only"
-num_images = "gpt"
-aspect_ratio = "gpt"
-background = "gpt"
-inference = "gpt"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_legacy"
+background = "available"
+inference = "gpt_image"
+safety_checker = "unavailable"
+output_format = "gpt_image_legacy"
+output_compression = "gpt_image_legacy"
+input_fidelity = "gpt_image_legacy"
+
+[gpt-image-2]
+sdk = "azure_rest_img_gen"
+model_type = "img_gen"
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 8, output = 30 }
+
+[gpt-image-2.rules]
+prompt = "positive_only"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_2"
+background = "unavailable"
+inference = "gpt_image"
safety_checker = "unavailable"
-output_format = "gpt"
+output_format = "unavailable"
+output_compression = "unavailable"
+input_images = "gpt_image"
+input_fidelity = "unavailable"
diff --git a/pipelex/kit/configs/inference/backends/fal.toml b/pipelex/kit/configs/inference/backends/fal.toml
index d79251ef0..2a4d03e12 100644
--- a/pipelex/kit/configs/inference/backends/fal.toml
+++ b/pipelex/kit/configs/inference/backends/fal.toml
@@ -38,6 +38,7 @@ outputs = ["image"]
costs = { input = 0.05, output = 0.0 }
[flux-pro.rules]
+model_choice = "model_id"
prompt = "positive_only"
num_images = "fal"
aspect_ratio = "flux"
@@ -53,6 +54,7 @@ outputs = ["image"]
costs = { input = 0.05, output = 0.0 }
["flux-pro/v1.1".rules]
+model_choice = "model_id"
prompt = "positive_only"
num_images = "fal"
aspect_ratio = "flux"
@@ -68,6 +70,7 @@ outputs = ["image"]
costs = { input = 0.06, output = 0.0 }
["flux-pro/v1.1-ultra".rules]
+model_choice = "model_id"
prompt = "positive_only"
num_images = "fal"
aspect_ratio = "flux_11_ultra"
@@ -83,6 +86,7 @@ outputs = ["image"]
costs = { input = 0.05, output = 0.0 }
[flux-2.rules]
+model_choice = "model_id"
prompt = "positive_only"
num_images = "fal"
aspect_ratio = "flux"
@@ -99,6 +103,7 @@ outputs = ["image"]
costs = { input = 0.0003, output = 0.0 }
[fast-lightning-sdxl.rules]
+model_choice = "model_id"
prompt = "positive_only"
num_images = "fal"
aspect_ratio = "flux"
diff --git a/pipelex/kit/configs/inference/backends/huggingface.toml b/pipelex/kit/configs/inference/backends/huggingface.toml
index 2fd0faf8b..b07673cfa 100644
--- a/pipelex/kit/configs/inference/backends/huggingface.toml
+++ b/pipelex/kit/configs/inference/backends/huggingface.toml
@@ -39,6 +39,7 @@ variant = "fal-ai"
# variant = "replicate"
[qwen-image.rules]
+model_choice = "model_id"
prompt = "with_negative"
aspect_ratio = "qwen_image"
inference = "qwen_image"
diff --git a/pipelex/kit/configs/inference/backends/openai.toml b/pipelex/kit/configs/inference/backends/openai.toml
index c9d9509aa..b75142169 100644
--- a/pipelex/kit/configs/inference/backends/openai.toml
+++ b/pipelex/kit/configs/inference/backends/openai.toml
@@ -237,6 +237,14 @@ outputs = ["text", "structured"]
costs = { input = 0.2, output = 1.25 }
thinking_mode = "manual"
+# --- GPT-5.5 Series -----------------------------------------------------------
+["gpt-5.5"]
+inputs = ["text", "images", "pdf"]
+outputs = ["text", "structured"]
+costs = { input = 5.0, output = 30.0 }
+valued_constraints = { fixed_temperature = 1 }
+thinking_mode = "manual"
+
################################################################################
# IMAGE GENERATION MODELS
################################################################################
@@ -245,21 +253,100 @@ thinking_mode = "manual"
[gpt-image-1]
sdk = "openai_img_gen"
model_type = "img_gen"
-inputs = ["text"]
+inputs = ["text", "images"]
outputs = ["image"]
costs = { input = 10, output = 40 }
+[gpt-image-1.rules]
+model_choice = "model_id"
+prompt = "positive_only"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_legacy"
+background = "available"
+inference = "gpt_image"
+safety_checker = "openai_moderation"
+output_format = "gpt_image_legacy"
+output_compression = "gpt_image_legacy"
+input_images = "gpt_image"
+input_fidelity = "gpt_image_legacy"
+
[gpt-image-1-mini]
sdk = "openai_img_gen"
model_type = "img_gen"
-inputs = ["text"]
+inputs = ["text", "images"]
outputs = ["image"]
costs = { input = 2.5, output = 8 }
+[gpt-image-1-mini.rules]
+model_choice = "model_id"
+prompt = "positive_only"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_legacy"
+background = "available"
+inference = "gpt_image"
+safety_checker = "openai_moderation"
+output_format = "gpt_image_legacy"
+output_compression = "gpt_image_legacy"
+input_images = "gpt_image"
+input_fidelity = "gpt_image_legacy"
+
["gpt-image-1.5"]
sdk = "openai_img_gen"
model_type = "img_gen"
model_id = "gpt-image-1.5"
-inputs = ["text"]
+inputs = ["text", "images"]
outputs = ["image"]
costs = { input = 8, output = 32 }
+
+["gpt-image-1.5".rules]
+model_choice = "model_id"
+prompt = "positive_only"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_legacy"
+background = "available"
+inference = "gpt_image"
+safety_checker = "openai_moderation"
+output_format = "gpt_image_legacy"
+output_compression = "gpt_image_legacy"
+input_images = "gpt_image"
+input_fidelity = "gpt_image_legacy"
+
+[gpt-image-2-2026-04-21]
+sdk = "openai_img_gen"
+model_type = "img_gen"
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 8, output = 30 }
+
+[gpt-image-2-2026-04-21.rules]
+model_choice = "model_id"
+prompt = "positive_only"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_2"
+background = "unavailable"
+inference = "gpt_image"
+safety_checker = "unavailable"
+output_format = "unavailable"
+output_compression = "unavailable"
+input_images = "gpt_image"
+input_fidelity = "unavailable"
+
+[gpt-image-2]
+sdk = "openai_img_gen"
+model_type = "img_gen"
+inputs = ["text", "images"]
+outputs = ["image"]
+costs = { input = 8, output = 30 }
+
+[gpt-image-2.rules]
+model_choice = "model_id"
+prompt = "positive_only"
+num_images = "gpt_image"
+aspect_ratio = "gpt_image_2"
+background = "unavailable"
+inference = "gpt_image"
+safety_checker = "unavailable"
+output_format = "unavailable"
+output_compression = "unavailable"
+input_images = "gpt_image"
+input_fidelity = "unavailable"
diff --git a/pipelex/kit/configs/inference/backends/pipelex_gateway_models.md b/pipelex/kit/configs/inference/backends/pipelex_gateway_models.md
index d457029b0..d497327a9 100644
--- a/pipelex/kit/configs/inference/backends/pipelex_gateway_models.md
+++ b/pipelex/kit/configs/inference/backends/pipelex_gateway_models.md
@@ -125,7 +125,7 @@ For configuration details, see the [documentation](https://docs.pipelex.com/late
<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
</tr>
<tr>
-<td>gemini-3.0-flash-preview</td>
+<td>gemini-3.0-flash</td>
<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
@@ -141,7 +141,15 @@ For configuration details, see the [documentation](https://docs.pipelex.com/late
<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
</tr>
<tr>
-<td>gemini-3.1-flash-lite-preview</td>
+<td>gemini-3.1-flash-lite</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
+<td>gemini-3.1-pro</td>
<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
@@ -333,6 +341,14 @@ For configuration details, see the [documentation](https://docs.pipelex.com/late
<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
</tr>
<tr>
+<td>gpt-5.5</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
<td>gpt-oss-120b</td>
<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
<td style="text-align:center;background-color:rgba(33,150,243,0.15)">❌</td>
@@ -554,6 +570,12 @@ For configuration details, see the [documentation](https://docs.pipelex.com/late
<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
</tr>
<tr>
+<td>gpt-image-2</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
+<td style="text-align:center;background-color:rgba(76,175,80,0.15)">✅</td>
+</tr>
+<tr>
<td>nano-banana</td>
<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
<td style="text-align:center;background-color:rgba(33,150,243,0.15)">✅</td>
@@ -576,6 +598,6 @@ For configuration details, see the [documentation](https://docs.pipelex.com/late
> **AUTO-GENERATED FILE** - Do not edit manually.
-> Last updated: 2026-04-17T12:23:17Z
+> Last updated: 2026-04-28T11:06:01Z
>
> Run `pipelex-dev update-gateway-models` or `make ugm` to regenerate.
\ No newline at end of file
diff --git a/pipelex/kit/configs/inference/backends/pipelex_gateway_models_plain.md b/pipelex/kit/configs/inference/backends/pipelex_gateway_models_plain.md
index 0ecadf2ff..b2f8ddcdf 100644
--- a/pipelex/kit/configs/inference/backends/pipelex_gateway_models_plain.md
+++ b/pipelex/kit/configs/inference/backends/pipelex_gateway_models_plain.md
@@ -46,13 +46,16 @@ For configuration details, see the [documentation](https://docs.pipelex.com/late
- **gemini-2.5-pro**
- inputs: text, images, pdf
- outputs: text, structured
-- **gemini-3.0-flash-preview**
+- **gemini-3.0-flash**
- inputs: text, images, pdf
- outputs: text, structured
- **gemini-3.0-pro**
- inputs: text, images, pdf
- outputs: text, structured
-- **gemini-3.1-flash-lite-preview**
+- **gemini-3.1-flash-lite**
+ - inputs: text, images, pdf
+ - outputs: text, structured
+- **gemini-3.1-pro**
- inputs: text, images, pdf
- outputs: text, structured
- **gemini-flash-latest**
@@ -124,6 +127,9 @@ For configuration details, see the [documentation](https://docs.pipelex.com/late
- **gpt-5.4-pro**
- inputs: text, images
- outputs: text, structured
+- **gpt-5.5**
+ - inputs: text, images
+ - outputs: text, structured
- **gpt-oss-120b**
- inputs: text
- outputs: text, structured
@@ -202,6 +208,9 @@ For configuration details, see the [documentation](https://docs.pipelex.com/late
- **gpt-image-1.5**
- inputs: text, images
- outputs: image
+- **gpt-image-2**
+ - inputs: text, images
+ - outputs: image
- **nano-banana**
- inputs: text, images
- outputs: image
@@ -214,6 +223,6 @@ For configuration details, see the [documentation](https://docs.pipelex.com/late
> **AUTO-GENERATED FILE** - Do not edit manually.
-> Last updated: 2026-04-17T12:23:17Z
+> Last updated: 2026-04-28T11:06:01Z
>
> Run `pipelex-dev update-gateway-models` or `make ugm` to regenerate.
\ No newline at end of file
diff --git a/pipelex/kit/configs/inference/deck/2_img_gen_deck.toml b/pipelex/kit/configs/inference/deck/2_img_gen_deck.toml
index 3436109f5..33907ae21 100644
--- a/pipelex/kit/configs/inference/deck/2_img_gen_deck.toml
+++ b/pipelex/kit/configs/inference/deck/2_img_gen_deck.toml
@@ -26,7 +26,7 @@ choice_default = "$gen-image"
####################################################################################################
[img_gen.aliases]
-best-gpt = "gpt-image-1.5"
+best-gpt = "gpt-image-2"
best-gemini = "nano-banana-2"
default-general = "nano-banana"
diff --git a/pipelex/pipe_operators/img_gen/pipe_img_gen.py b/pipelex/pipe_operators/img_gen/pipe_img_gen.py
index 02b8bfe4c..d80a42a27 100644
--- a/pipelex/pipe_operators/img_gen/pipe_img_gen.py
+++ b/pipelex/pipe_operators/img_gen/pipe_img_gen.py
@@ -7,7 +7,8 @@ from pipelex import log
from pipelex.cogt.content_generation.content_generator_dry import ContentGeneratorDry
from pipelex.cogt.content_generation.content_generator_protocol import ContentGeneratorProtocol
from pipelex.cogt.img_gen.img_gen_job_components import AspectRatio, Background, ImgGenJobParams
-from pipelex.cogt.img_gen.img_gen_setting import ImgGenModelChoice, ImgGenSetting
+from pipelex.cogt.img_gen.img_gen_param_support import ImgGenParamSupport
+from pipelex.cogt.img_gen.img_gen_setting import ImgGenModelChoice, ImgGenSetting, ImgGenSettingValueError
from pipelex.cogt.model_backends.model_type import ModelType
from pipelex.cogt.models.model_deck_check import check_img_gen_choice_with_deck
from pipelex.config import get_config
@@ -66,6 +67,45 @@ class PipeImgGen(PipeOperator[PipeImgGenOutput]):
def validate_inputs_static(self):
if self.img_gen_choice:
check_img_gen_choice_with_deck(img_gen_choice=self.img_gen_choice)
+ self._validate_param_support_against_model_rules()
+
+ def _validate_param_support_against_model_rules(self) -> None:
+ """If `img_gen_choice` resolves to a concrete inference model with rules,
+ validate that explicitly-set blueprint params are accepted by those rules.
+
+ Skipped silently when the choice is a preset/alias/waterfall whose target
+ cannot be resolved at static-validation time, or when the resolved spec
+ has no rules attached.
+ """
+ if self.img_gen_choice is None:
+ return
+ model_deck = get_model_deck()
+ try:
+ img_gen_setting = model_deck.get_img_gen_setting(self.img_gen_choice)
+ except ImgGenSettingValueError:
+ return
+ spec = model_deck.get_optional_inference_model(
+ model_handle=img_gen_setting.model,
+ model_type=ModelType.IMG_GEN,
+ )
+ if spec is None or spec.rules is None:
+ return
+ unsupported = ImgGenParamSupport.check_blueprint_params(
+ rules=spec.rules,
+ aspect_ratio=self.aspect_ratio,
+ background=self.background,
+ output_format=self.output_format,
+ model_name=img_gen_setting.model,
+ )
+ if unsupported:
+ joined = "; ".join(unsupported)
+ msg = f"PipeImgGen '{self.code}' uses parameter values not supported by model '{img_gen_setting.model}': {joined}"
+ raise PipeValidationError(
+ message=msg,
+ error_type=PipeValidationErrorType.UNKNOWN_VALIDATION_ERROR,
+ domain_code=self.domain_code,
+ pipe_code=self.code,
+ )
@override
def validate_inputs_with_library(self):
diff --git a/pipelex/plugins/azure_rest/azure_img_gen_worker.py b/pipelex/plugins/azure_rest/azure_img_gen_worker.py
index 99022a740..8db1dfae3 100644
--- a/pipelex/plugins/azure_rest/azure_img_gen_worker.py
+++ b/pipelex/plugins/azure_rest/azure_img_gen_worker.py
@@ -8,10 +8,12 @@ from pipelex.cogt.img_gen.img_gen_args_factory import ImgGenArgsFactory
from pipelex.cogt.img_gen.img_gen_job import ImgGenJob
from pipelex.cogt.img_gen.img_gen_worker_abstract import ImgGenWorkerAbstract
from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
+from pipelex.cogt.usage.token_category import NbTokensByCategoryDict, TokenCategory
from pipelex.hub import get_models_manager
from pipelex.plugins.plugin import Plugin
from pipelex.reporting.reporting_protocol import ReportingProtocol
from pipelex.system.exceptions import CredentialsError
+from pipelex.tools.log.log import log
class AzureCredentialsError(CredentialsError):
@@ -75,6 +77,7 @@ class AzureImgGenWorker(ImgGenWorkerAbstract):
img_gen_job=img_gen_job,
nb_images=nb_images,
model_id=self.inference_model.model_id,
+ model_name=self.inference_model.name,
)
args_dict["prompt"] = img_gen_job.img_gen_prompt.positive_text
@@ -95,11 +98,21 @@ class AzureImgGenWorker(ImgGenWorkerAbstract):
"Content-Type": "application/json",
},
json=args_dict,
- timeout=180.0,
+ timeout=600.0,
)
response.raise_for_status()
response_dict = response.json()
+ # Extract usage tokens if available
+ if (usage_dict := response_dict.get("usage")) and (img_gen_tokens_usage := img_gen_job.job_report.img_gen_tokens_usage):
+ log.debug(usage_dict, title="Azure img gen usage")
+ nb_tokens: NbTokensByCategoryDict = {}
+ if input_tokens := usage_dict.get("prompt_tokens") or usage_dict.get("input_tokens"):
+ nb_tokens[TokenCategory.INPUT] = input_tokens
+ if output_tokens := usage_dict.get("completion_tokens") or usage_dict.get("output_tokens"):
+ nb_tokens[TokenCategory.OUTPUT] = output_tokens
+ img_gen_tokens_usage.nb_tokens_by_category = nb_tokens
+
response_output_format: str | None = response_dict.get("output_format")
if not response_output_format:
msg = "No output format received from Azure"
diff --git a/pipelex/plugins/fal/fal_img_gen_worker.py b/pipelex/plugins/fal/fal_img_gen_worker.py
index 1155479b6..707564927 100644
--- a/pipelex/plugins/fal/fal_img_gen_worker.py
+++ b/pipelex/plugins/fal/fal_img_gen_worker.py
@@ -42,8 +42,12 @@ class FalImgGenWorker(ImgGenWorkerAbstract):
img_gen_job=img_gen_job,
nb_images=nb_images,
model_id=self.inference_model.model_id,
+ model_name=self.inference_model.name,
)
- fal_application = self.inference_model.model_id
+ fal_application = args_dict.pop("model", None)
+ if fal_application is None:
+ msg = f"Model '{self.inference_model.name}' rules must include a 'model_choice' entry"
+ raise ImgGenParameterError(msg)
log.verbose(args_dict, title=f"Fal arguments, application={fal_application}")
handler = await self.fal_async_client.submit(
application=fal_application,
diff --git a/pipelex/plugins/gateway/gateway_img_gen_worker.py b/pipelex/plugins/gateway/gateway_img_gen_worker.py
index 6abf53153..8921bf3de 100644
--- a/pipelex/plugins/gateway/gateway_img_gen_worker.py
+++ b/pipelex/plugins/gateway/gateway_img_gen_worker.py
@@ -21,6 +21,7 @@ from pipelex.plugins.fal.fal_poller import FalPoller
from pipelex.plugins.gateway.gateway_deck import GatewayDeck
from pipelex.plugins.gateway.gateway_factory import GatewayFactory
from pipelex.plugins.gateway.gateway_schemas import GatewayImgGenAzureFlux2Pro, GatewayImgGenAzureGptImage
+from pipelex.tools.log.log import log
from pipelex.tools.misc.filetype_utils import detect_file_type_from_bytes
from pipelex.tools.misc.image_utils import ImageFormat
from pipelex.tools.typing.pydantic_utils import format_pydantic_validation_error
@@ -68,10 +69,12 @@ class GatewayImgGenWorker(ImgGenWorkerAbstract):
img_gen_job=img_gen_job,
nb_images=nb_images,
model_id=self.inference_model.model_id,
+ model_name=self.inference_model.name,
)
endpoint_path = (self.inference_model.extra_headers or {}).get("endpoint_path") or f"/{self.inference_model.model_id}"
config_id = GatewayDeck.get_config_id(headers=self.inference_model.extra_headers or {})
+ log.debug(args_dict, title="Gateway img gen args")
try:
# TODO: add portkey tracing headers when enabled
response = await self.portkey_client.with_options(config=config_id).post( # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType]
diff --git a/pipelex/plugins/huggingface/huggingface_img_gen_worker.py b/pipelex/plugins/huggingface/huggingface_img_gen_worker.py
index f216ec381..6c2a74536 100644
--- a/pipelex/plugins/huggingface/huggingface_img_gen_worker.py
+++ b/pipelex/plugins/huggingface/huggingface_img_gen_worker.py
@@ -42,9 +42,13 @@ class HuggingFaceImgGenWorker(ImgGenWorkerAbstract):
img_gen_job=img_gen_job,
nb_images=1,
model_id=self.inference_model.model_id,
+ model_name=self.inference_model.name,
)
prompt = args_dict.pop("prompt")
- model_id = self.inference_model.model_id
+ model_id = args_dict.pop("model", None)
+ if model_id is None:
+ msg = f"Model '{self.inference_model.name}' rules must include a 'model_choice' entry"
+ raise ImgGenParameterError(msg)
return await self.hf_async_client.text_to_image(
prompt=prompt,
model=model_id,
diff --git a/pipelex/plugins/openai/openai_img_gen_factory.py b/pipelex/plugins/openai/openai_img_gen_factory.py
index 89db97dda..f2b1dedec 100644
--- a/pipelex/plugins/openai/openai_img_gen_factory.py
+++ b/pipelex/plugins/openai/openai_img_gen_factory.py
@@ -1,84 +1,138 @@
-from typing import Literal
+from typing import ClassVar, Literal
from openai import Omit, omit
+from pipelex import log
from pipelex.cogt.exceptions import ImgGenParameterError
-from pipelex.cogt.img_gen.img_gen_job_components import AspectRatio, Background, Quality
-from pipelex.tools.misc.image_utils import ImageFormat
+from pipelex.cogt.image.image_size import ImageSize
+from pipelex.cogt.img_gen.img_gen_job_components import AspectRatio, InputFidelity
-GptImage1SizeType = Literal["1024x1024", "1536x1024", "1024x1536"]
-GptImage1OutputFormatType = Literal["png", "jpeg", "webp"]
-GptImage1ModerationType = Literal["low", "auto"] | Omit
-GptImage1QualityType = Literal["low", "medium", "high"]
-GptImage1BackgroundType = Literal["transparent", "opaque", "auto"]
+OpenAIImageLegacySizeType = Literal["1024x1024", "1536x1024", "1024x1536"]
+OpenAIImageModerationType = Literal["low", "auto"] | Omit
+OpenAIImageInputFidelityType = Literal["low", "high"]
class OpenAIImgGenFactory:
+ LEGACY_ASPECT_RATIO_TO_SIZE: ClassVar[dict[AspectRatio, tuple[OpenAIImageLegacySizeType, int, int]]] = {
+ AspectRatio.SQUARE: ("1024x1024", 1024, 1024),
+ AspectRatio.LANDSCAPE_3_2: ("1536x1024", 1536, 1024),
+ AspectRatio.PORTRAIT_2_3: ("1024x1536", 1024, 1536),
+ }
+ LEGACY_SIZE_TO_DIMENSIONS: ClassVar[dict[str, tuple[OpenAIImageLegacySizeType, int, int]]] = {
+ size: (size, width, height) for size, width, height in LEGACY_ASPECT_RATIO_TO_SIZE.values()
+ }
+
+ GPT_IMAGE_2_ASPECT_RATIO_TO_SIZE: ClassVar[dict[AspectRatio, tuple[int, int]]] = {
+ AspectRatio.SQUARE: (1024, 1024),
+ AspectRatio.LANDSCAPE_4_3: (1536, 1152),
+ AspectRatio.LANDSCAPE_3_2: (1536, 1024),
+ AspectRatio.LANDSCAPE_16_9: (1536, 864),
+ AspectRatio.LANDSCAPE_21_9: (1792, 768),
+ AspectRatio.PORTRAIT_3_4: (1152, 1536),
+ AspectRatio.PORTRAIT_2_3: (1024, 1536),
+ AspectRatio.PORTRAIT_9_16: (864, 1536),
+ AspectRatio.PORTRAIT_9_21: (768, 1792),
+ }
+ GPT_IMAGE_2_EDGE_MULTIPLE: ClassVar[int] = 16
+ GPT_IMAGE_2_MAX_EDGE_EXCLUSIVE: ClassVar[int] = 3840
+ GPT_IMAGE_2_MAX_LONG_SHORT_RATIO: ClassVar[float] = 3.0
+ GPT_IMAGE_2_MIN_PIXELS: ClassVar[int] = 655_360
+ GPT_IMAGE_2_MAX_PIXELS: ClassVar[int] = 8_294_400
+ GPT_IMAGE_2_RELIABILITY_PIXELS: ClassVar[int] = 2560 * 1440
+
@classmethod
- def image_size_for_gpt_image_1(cls, aspect_ratio: AspectRatio) -> tuple[GptImage1SizeType, int, int]:
- match aspect_ratio:
- case AspectRatio.SQUARE:
- return "1024x1024", 1024, 1024
- case AspectRatio.LANDSCAPE_3_2:
- return "1536x1024", 1536, 1024
- case AspectRatio.PORTRAIT_2_3:
- return "1024x1536", 1024, 1536
- case (
- AspectRatio.LANDSCAPE_4_3
- | AspectRatio.LANDSCAPE_16_9
- | AspectRatio.LANDSCAPE_21_9
- | AspectRatio.PORTRAIT_3_4
- | AspectRatio.PORTRAIT_9_16
- | AspectRatio.PORTRAIT_9_21
- ):
- msg = f"Aspect ratio '{aspect_ratio}' is not supported by GPT Image 1 model"
+ def size_for_legacy_openai_image(
+ cls,
+ *,
+ model_name: str,
+ aspect_ratio: AspectRatio,
+ size: ImageSize | None,
+ ) -> tuple[OpenAIImageLegacySizeType, int, int]:
+ if size is not None:
+ size_string = cls._size_to_string(size)
+ if legacy_size := cls.LEGACY_SIZE_TO_DIMENSIONS.get(size_string):
+ return legacy_size
+ else:
+ supported_sizes = ", ".join(sorted(cls.LEGACY_SIZE_TO_DIMENSIONS))
+ msg = f"Size '{size_string}' is not supported by OpenAI image model '{model_name}'. Supported sizes are: {supported_sizes}"
raise ImgGenParameterError(msg)
+ if legacy_size := cls.LEGACY_ASPECT_RATIO_TO_SIZE.get(aspect_ratio):
+ return legacy_size
+
+ supported_aspect_ratios = ", ".join(aspect_ratio.value for aspect_ratio in cls.LEGACY_ASPECT_RATIO_TO_SIZE)
+ msg = (
+ f"Aspect ratio '{aspect_ratio}' is not supported by OpenAI image model '{model_name}'. "
+ f"Supported aspect ratios are: {supported_aspect_ratios}"
+ )
+ raise ImgGenParameterError(msg)
+
@classmethod
- def output_format_for_gpt_image_1(cls, output_format: ImageFormat | None) -> GptImage1OutputFormatType | None:
- """This method only converts the OutputFormat StrEnum value to a Literal, as expected by the OpenAI API"""
- if output_format is None:
- return None
- match output_format:
- case ImageFormat.PNG:
- return "png"
- case ImageFormat.JPEG:
- return "jpeg"
- case ImageFormat.WEBP:
- return "webp"
+ def size_for_gpt_image_2(
+ cls,
+ *,
+ model_name: str,
+ aspect_ratio: AspectRatio,
+ size: ImageSize | None,
+ ) -> tuple[str, int, int]:
+ if size is None:
+ width, height = cls.GPT_IMAGE_2_ASPECT_RATIO_TO_SIZE[aspect_ratio]
+ size = ImageSize(width=width, height=height)
+ cls.validate_gpt_image_2_size(model_name=model_name, size=size)
+ return cls._size_to_string(size), size.width, size.height
@classmethod
- def moderation_for_gpt_image_1(cls, is_moderated: bool | None) -> GptImage1ModerationType:
+ def validate_gpt_image_2_size(cls, *, model_name: str, size: ImageSize) -> None:
+ size_string = cls._size_to_string(size)
+ width = size.width
+ height = size.height
+
+ if width <= 0 or height <= 0:
+ msg = f"Size '{size_string}' is invalid for OpenAI image model '{model_name}': width and height must be positive"
+ raise ImgGenParameterError(msg)
+
+ if width % cls.GPT_IMAGE_2_EDGE_MULTIPLE != 0 or height % cls.GPT_IMAGE_2_EDGE_MULTIPLE != 0:
+ msg = f"Size '{size_string}' is invalid for OpenAI image model '{model_name}': width and height must be multiples of 16"
+ raise ImgGenParameterError(msg)
+
+ max_edge = max(width, height)
+ if max_edge >= cls.GPT_IMAGE_2_MAX_EDGE_EXCLUSIVE:
+ msg = f"Size '{size_string}' is invalid for OpenAI image model '{model_name}': max edge must be less than 3840 pixels"
+ raise ImgGenParameterError(msg)
+
+ min_edge = min(width, height)
+ long_short_ratio = max_edge / min_edge
+ if long_short_ratio > cls.GPT_IMAGE_2_MAX_LONG_SHORT_RATIO:
+ msg = f"Size '{size_string}' is invalid for OpenAI image model '{model_name}': long-to-short edge ratio must be at most 3:1"
+ raise ImgGenParameterError(msg)
+
+ total_pixels = width * height
+ if total_pixels < cls.GPT_IMAGE_2_MIN_PIXELS:
+ msg = f"Size '{size_string}' is invalid for OpenAI image model '{model_name}': total pixels must be at least {cls.GPT_IMAGE_2_MIN_PIXELS}"
+ raise ImgGenParameterError(msg)
+ if total_pixels > cls.GPT_IMAGE_2_MAX_PIXELS:
+ msg = f"Size '{size_string}' is invalid for OpenAI image model '{model_name}': total pixels must be at most {cls.GPT_IMAGE_2_MAX_PIXELS}"
+ raise ImgGenParameterError(msg)
+
+ if total_pixels > cls.GPT_IMAGE_2_RELIABILITY_PIXELS:
+ log.warning(f"Size '{size_string}' is valid for OpenAI image model '{model_name}', but it is above the 2560x1440 reliability boundary.")
+
+ @classmethod
+ def moderation_for_openai_image(cls, is_moderated: bool | None) -> OpenAIImageModerationType:
if is_moderated is None:
return omit
- elif is_moderated:
+ if is_moderated:
return "low"
- else:
- return "auto"
+ return "auto"
@classmethod
- def quality_for_gpt_image_1(cls, quality: Quality) -> GptImage1QualityType:
- """This method only converts the Quality string value as a Literal, as expected by the OpenAI API"""
- match quality:
- case Quality.LOW:
+ def input_fidelity_for_openai_image(cls, input_fidelity: InputFidelity) -> OpenAIImageInputFidelityType:
+ match input_fidelity:
+ case InputFidelity.LOW:
return "low"
- case Quality.MEDIUM:
- return "medium"
- case Quality.HIGH:
+ case InputFidelity.HIGH:
return "high"
- @classmethod
- def background_for_gpt_image_1(cls, background: Background) -> GptImage1BackgroundType:
- """This method only converts the Background string value as a Literal, as expected by the OpenAI API"""
- match background:
- case Background.TRANSPARENT:
- return "transparent"
- case Background.OPAQUE:
- return "opaque"
- case Background.AUTO:
- return "auto"
-
- @classmethod
- def output_compression_for_gpt_image_1(cls) -> int:
- """This method only converts the OutputCompression int value as a Literal, as expected by the OpenAI API"""
- return 100
+ @staticmethod
+ def _size_to_string(size: ImageSize) -> str:
+ return f"{size.width}x{size.height}"
diff --git a/pipelex/plugins/openai/openai_img_gen_worker.py b/pipelex/plugins/openai/openai_img_gen_worker.py
index 4cd111239..154f5aabf 100644
--- a/pipelex/plugins/openai/openai_img_gen_worker.py
+++ b/pipelex/plugins/openai/openai_img_gen_worker.py
@@ -1,18 +1,22 @@
-from typing import TYPE_CHECKING, Any
+import base64
+from typing import TYPE_CHECKING, Any, cast
import openai
from typing_extensions import override
-from pipelex.cogt.exceptions import ImgGenGenerationError, SdkTypeError
+from pipelex import log
+from pipelex.cogt.exceptions import ImgGenGenerationError, ImgGenParameterError, SdkTypeError
from pipelex.cogt.image.generated_image import GeneratedImageRawDetails
from pipelex.cogt.image.image_size import ImageSize
+from pipelex.cogt.img_gen.img_gen_args_factory import ImgGenArgsFactory
from pipelex.cogt.img_gen.img_gen_job import ImgGenJob
-from pipelex.cogt.img_gen.img_gen_job_components import Quality
from pipelex.cogt.img_gen.img_gen_worker_abstract import ImgGenWorkerAbstract
from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
from pipelex.cogt.usage.token_category import NbTokensByCategoryDict, TokenCategory
-from pipelex.plugins.openai.openai_img_gen_factory import OpenAIImgGenFactory
from pipelex.reporting.reporting_protocol import ReportingProtocol
+from pipelex.tools.misc.base64_utils import extract_base64_str_from_base64_url_if_possible
+from pipelex.tools.misc.filetype_utils import detect_file_type_from_bytes
+from pipelex.tools.misc.image_utils import ImageFormat
if TYPE_CHECKING:
from openai.types.images_response import ImagesResponse, Usage
@@ -47,32 +51,33 @@ class OpenAIImgGenWorker(ImgGenWorkerAbstract):
img_gen_job: ImgGenJob,
nb_images: int,
) -> list[GeneratedImageRawDetails]:
- image_size, width, height = OpenAIImgGenFactory.image_size_for_gpt_image_1(aspect_ratio=img_gen_job.job_params.aspect_ratio)
- output_format = OpenAIImgGenFactory.output_format_for_gpt_image_1(output_format=img_gen_job.job_params.output_format)
- moderation = OpenAIImgGenFactory.moderation_for_gpt_image_1(is_moderated=img_gen_job.job_params.is_moderated)
- background = OpenAIImgGenFactory.background_for_gpt_image_1(background=img_gen_job.job_params.background)
- quality = OpenAIImgGenFactory.quality_for_gpt_image_1(quality=img_gen_job.job_params.quality or Quality.LOW)
- output_compression = OpenAIImgGenFactory.output_compression_for_gpt_image_1()
- images_response: ImagesResponse = await self.openai_client.images.generate(
- prompt=img_gen_job.img_gen_prompt.positive_text,
- model=self.inference_model.model_id,
- moderation=moderation,
- background=background,
- quality=quality,
- size=image_size,
- output_format=output_format,
- output_compression=output_compression,
- n=nb_images,
+ if self.inference_model.rules is None:
+ msg = f"Model '{self.inference_model.name}' does not have rules configured"
+ raise ImgGenParameterError(msg)
+
+ args_dict = await ImgGenArgsFactory.make_args_for_model(
+ model_rules=self.inference_model.rules,
+ img_gen_job=img_gen_job,
+ nb_images=nb_images,
+ model_id=self.inference_model.model_id,
+ model_name=self.inference_model.name,
)
+
+ images_response: ImagesResponse
+ if image_arg := args_dict.get("image"):
+ args_dict["image"] = self._convert_image_data_urls_for_openai_sdk(image_arg=image_arg)
+ if args_dict.pop("moderation", None) is not None:
+ log.warning("OpenAI images.edit does not accept 'moderation'; dropping the kwarg")
+ images_response = cast("ImagesResponse", await self.openai_client.images.edit(**args_dict))
+ else:
+ images_response = cast("ImagesResponse", await self.openai_client.images.generate(**args_dict))
+
if not images_response.data:
msg = "No result from OpenAI"
raise ImgGenGenerationError(msg)
response_output_format: str | None = images_response.output_format
- if response_output_format is None:
- msg = "No output format received from OpenAI"
- raise ImgGenGenerationError(msg)
- size: str | None = images_response.size
+ size: str | None = images_response.size or self._get_requested_size(args_dict=args_dict)
if not size:
msg = "No size received from OpenAI"
raise ImgGenGenerationError(msg)
@@ -103,11 +108,47 @@ class OpenAIImgGenWorker(ImgGenWorkerAbstract):
msg = "No base64 image data received from OpenAI"
raise ImgGenGenerationError(msg)
+ image_format = response_output_format
+ if image_format is None:
+ image_bytes = base64.b64decode(base64_str)
+ file_type = detect_file_type_from_bytes(image_bytes)
+ image_format = ImageFormat.from_mime_type(mime_type=file_type.mime).value
+
generated_images.append(
GeneratedImageRawDetails(
base64_str=base64_str,
size=ImageSize(width=width, height=height),
- image_format=response_output_format,
+ image_format=image_format,
),
)
return generated_images
+
+ @staticmethod
+ def _convert_image_data_urls_for_openai_sdk(image_arg: Any) -> list[tuple[str, bytes, str]]:
+ """Convert shared GPT Image data URLs into the OpenAI SDK's multipart file tuples."""
+ if not isinstance(image_arg, list):
+ msg = f"OpenAI image edit expected a list of image data URLs, got '{type(image_arg).__name__}'"
+ raise ImgGenParameterError(msg)
+
+ image_data_urls = cast("list[Any]", image_arg)
+ image_files: list[tuple[str, bytes, str]] = []
+ for index, image_data_url in enumerate(image_data_urls):
+ if not isinstance(image_data_url, str):
+ msg = f"OpenAI image edit expected image #{index} to be a data URL, got '{type(image_data_url).__name__}'"
+ raise ImgGenParameterError(msg)
+ extracted = extract_base64_str_from_base64_url_if_possible(possibly_base64_url=image_data_url)
+ if extracted is None:
+ msg = "OpenAI image edit expected base64 data URLs from the shared image argument factory"
+ raise ImgGenParameterError(msg)
+ base64_str, mime_type = extracted
+ file_extension = mime_type.split("/", 1)[1].replace("jpeg", "jpg")
+ image_bytes = base64.b64decode(base64_str)
+ image_files.append((f"image_{index}.{file_extension}", image_bytes, mime_type))
+ return image_files
+
+ @staticmethod
+ def _get_requested_size(args_dict: dict[str, Any]) -> str | None:
+ requested_size = args_dict.get("size")
+ if isinstance(requested_size, str):
+ return requested_size
+ return None
diff --git a/pipelex/system/pipelex_service/pipelex_details.py b/pipelex/system/pipelex_service/pipelex_details.py
index 04431ced0..e5cbd265a 100644
--- a/pipelex/system/pipelex_service/pipelex_details.py
+++ b/pipelex/system/pipelex_service/pipelex_details.py
@@ -2,7 +2,7 @@ from pipelex.tools.misc.hash_utils import hash_sha256
class PipelexDetails:
- REMOTE_CONFIG_URL = "https://pipelex-config.s3.eu-west-3.amazonaws.com/pipelex_remote_config_09.json"
+ REMOTE_CONFIG_URL = "https://pipelex-config.s3.eu-west-3.amazonaws.com/pipelex_remote_config_10.json"
PIPELEX_GATEWAY_API_KEY_VAR = "PIPELEX_GATEWAY_API_KEY"
@classmethod
diff --git a/tests/e2e/pipelex/pipes/pipe_operators/pipe_img_gen/test_pipe_img_gen_validation.py b/tests/e2e/pipelex/pipes/pipe_operators/pipe_img_gen/test_pipe_img_gen_validation.py
new file mode 100644
index 000000000..31b248aa3
--- /dev/null
+++ b/tests/e2e/pipelex/pipes/pipe_operators/pipe_img_gen/test_pipe_img_gen_validation.py
@@ -0,0 +1,140 @@
+"""End-to-end validation tests for PipeImgGen — drives validation through `validate_bundle`.
+
+Each test feeds a small synthetic `.mthds` bundle string into `validate_bundle`
+and asserts that the bundle validator raises (or doesn't) based on whether the
+PipeImgGen blueprint's parameter values are accepted by the model's rules.
+
+Mirrors the pattern used by the PipeFunc validation e2e tests.
+"""
+
+from __future__ import annotations
+
+import shutil
+import tempfile
+from pathlib import Path
+from typing import Iterator
+
+import pytest
+from pytest import MonkeyPatch
+
+from pipelex.cogt.model_backends.model_type import ModelType
+from pipelex.hub import get_console, get_model_deck
+from pipelex.pipelex import Pipelex
+from pipelex.pipeline.validate_bundle import ValidateBundleError, validate_bundle
+from pipelex.system.configuration.config_loader import config_manager
+from pipelex.system.runtime import IntegrationMode, runtime_manager
+from pipelex.tools.misc.toml_utils import load_toml_with_tomlkit, save_toml_to_path
+
+
[email protected](scope="class")
+def pipelex_routed_to_openai_for_e2e() -> Iterator[None]:
+ """Reload Pipelex with routing forced to the openai backend so img-gen rules
+ use the current taxonomy (legacy gpt-image-1 = GPT_IMAGE_LEGACY etc.).
+ """
+ Pipelex.teardown_if_needed()
+
+ routing_profile_name = "all_openai"
+ routing_monkeypatch = MonkeyPatch()
+ routing_profiles_path = Path(config_manager.routing_profiles_file_path)
+ routing_profiles_doc = load_toml_with_tomlkit(str(routing_profiles_path))
+ routing_profiles_doc["active"] = routing_profile_name
+ routing_override_dir = Path(tempfile.mkdtemp(prefix="pipelex-routing-pipe-img-gen-e2e-validation-"))
+ routing_override_path = routing_override_dir / routing_profiles_path.name
+ save_toml_to_path(routing_profiles_doc, str(routing_override_path))
+ routing_monkeypatch.setattr(
+ type(config_manager),
+ "routing_profiles_file_path",
+ property(lambda _self: str(routing_override_path)),
+ )
+ get_console().print("[cyan]Routing to backend:[/cyan] openai (for e2e validation test)")
+
+ try:
+ integration_mode = IntegrationMode.CI if runtime_manager.is_ci_testing else IntegrationMode.PYTEST
+ Pipelex.make(integration_mode=integration_mode)
+ except Exception:
+ routing_monkeypatch.undo()
+ shutil.rmtree(routing_override_dir, ignore_errors=True)
+ raise
+
+ yield
+
+ Pipelex.teardown_if_needed()
+ routing_monkeypatch.undo()
+ shutil.rmtree(routing_override_dir, ignore_errors=True)
+
+
+_BAD_BUNDLE_LEGACY_LANDSCAPE_4_3 = """\
+domain = "img_gen_validation_e2e"
+description = "E2E test: legacy model + landscape_4_3 must fail validation"
+
+[pipe.bad_landscape_4_3]
+type = "PipeImgGen"
+description = "Should fail: gpt-image-1 doesn't accept landscape_4_3"
+output = "Image"
+prompt = "A test prompt"
+model = "gpt-image-1"
+aspect_ratio = "landscape_4_3"
+"""
+
+_BAD_BUNDLE_GPT_IMAGE_2_TRANSPARENT = """\
+domain = "img_gen_validation_e2e"
+description = "E2E test: gpt-image-2 + transparent background must fail validation"
+
+[pipe.bad_gpt_image_2_transparent]
+type = "PipeImgGen"
+description = "Should fail: gpt-image-2 doesn't accept transparent background"
+output = "Image"
+prompt = "A test prompt"
+model = "gpt-image-2"
+background = "transparent"
+"""
+
+_GOOD_BUNDLE_LEGACY_SQUARE = """\
+domain = "img_gen_validation_e2e"
+description = "E2E test: legacy model + square must succeed"
+
+[pipe.good_legacy_square]
+type = "PipeImgGen"
+description = "Should succeed: gpt-image-1 accepts square"
+output = "Image"
+prompt = "A test prompt"
+model = "gpt-image-1"
+aspect_ratio = "square"
+"""
+
+
[email protected]("pipelex_routed_to_openai_for_e2e")
[email protected](loop_scope="class")
+class TestPipeImgGenE2EValidation:
+ """E2E: bad PipeImgGen blueprints must surface as ValidateBundleError at bundle-load time."""
+
+ async def test_validate_bundle_rejects_legacy_with_landscape_4_3(self) -> None:
+ if get_model_deck().get_optional_inference_model(model_handle="gpt-image-1", model_type=ModelType.IMG_GEN) is None:
+ pytest.skip("gpt-image-1 not available in current deck routing")
+
+ with pytest.raises(ValidateBundleError) as exc_info:
+ await validate_bundle(mthds_contents=[_BAD_BUNDLE_LEGACY_LANDSCAPE_4_3])
+
+ msg = str(exc_info.value)
+ assert "gpt-image-1" in msg
+ assert "landscape_4_3" in msg.lower()
+
+ async def test_validate_bundle_rejects_gpt_image_2_with_transparent(self) -> None:
+ if get_model_deck().get_optional_inference_model(model_handle="gpt-image-2", model_type=ModelType.IMG_GEN) is None:
+ pytest.skip("gpt-image-2 not available in current deck routing")
+
+ with pytest.raises(ValidateBundleError) as exc_info:
+ await validate_bundle(mthds_contents=[_BAD_BUNDLE_GPT_IMAGE_2_TRANSPARENT])
+
+ msg = str(exc_info.value).lower()
+ assert "gpt-image-2" in msg
+ assert "transparent" in msg
+
+ async def test_validate_bundle_accepts_legacy_with_square(self) -> None:
+ if get_model_deck().get_optional_inference_model(model_handle="gpt-image-1", model_type=ModelType.IMG_GEN) is None:
+ pytest.skip("gpt-image-1 not available in current deck routing")
+
+ result = await validate_bundle(mthds_contents=[_GOOD_BUNDLE_LEGACY_SQUARE])
+
+ assert len(result.pipes) == 1
+ assert result.pipes[0].code == "good_legacy_square"
diff --git a/tests/integration/pipelex/cogt/test_img2img.py b/tests/integration/pipelex/cogt/test_img2img.py
index 4aea1c6f1..c02fa66f1 100644
--- a/tests/integration/pipelex/cogt/test_img2img.py
+++ b/tests/integration/pipelex/cogt/test_img2img.py
@@ -14,6 +14,7 @@ from pipelex.hub import get_img_gen_worker
from pipelex.pipeline.job_metadata import JobMetadata
from pipelex.tools.misc.image_utils import ImageFormat
from tests.cases import ImageTestCases
+from tests.integration.pipelex.fixtures.img_gen_fixtures import skip_if_img_gen_params_unsupported
from tests.integration.pipelex.fixtures.model_combo import ModelCombo
PRIMARY_ID = "img2img_1"
@@ -91,6 +92,7 @@ class TestImageToImageGeneration:
background=Background.OPAQUE,
output_format=ImageFormat.PNG,
)
+ skip_if_img_gen_params_unsupported(img_gen_worker.inference_model, img_gen_job_params, has_input_images=True)
img_gen_job = ImgGenJobFactory.make_img_gen_job_from_prompt(
img_gen_prompt=img_gen_prompt,
@@ -147,6 +149,7 @@ class TestImageToImageGeneration:
background=Background.OPAQUE,
output_format=ImageFormat.PNG,
)
+ skip_if_img_gen_params_unsupported(img_gen_worker.inference_model, img_gen_job_params, has_input_images=True)
img_gen_job = ImgGenJobFactory.make_img_gen_job_from_prompt(
img_gen_prompt=img_gen_prompt,
@@ -208,6 +211,7 @@ class TestImageToImageGeneration:
background=Background.OPAQUE,
output_format=ImageFormat.PNG,
)
+ skip_if_img_gen_params_unsupported(img_gen_worker.inference_model, img_gen_job_params, has_input_images=True)
img_gen_job = ImgGenJobFactory.make_img_gen_job_from_prompt(
img_gen_prompt=img_gen_prompt,
@@ -264,6 +268,7 @@ class TestImageToImageGeneration:
background=Background.OPAQUE,
output_format=ImageFormat.PNG,
)
+ skip_if_img_gen_params_unsupported(img_gen_worker.inference_model, img_gen_job_params, has_input_images=True)
img_gen_job = ImgGenJobFactory.make_img_gen_job_from_prompt(
img_gen_prompt=img_gen_prompt,
diff --git a/tests/integration/pipelex/cogt/test_img_gen.py b/tests/integration/pipelex/cogt/test_img_gen.py
index 9924fb6b0..28830c777 100644
--- a/tests/integration/pipelex/cogt/test_img_gen.py
+++ b/tests/integration/pipelex/cogt/test_img_gen.py
@@ -7,6 +7,7 @@ from pipelex.cogt.img_gen.img_gen_job_factory import ImgGenJobFactory
from pipelex.hub import get_img_gen_worker, get_report_delegate
from pipelex.pipeline.job_metadata import JobMetadata
from pipelex.tools.misc.image_utils import ImageFormat
+from tests.integration.pipelex.fixtures.img_gen_fixtures import skip_if_img_gen_params_unsupported
from tests.integration.pipelex.fixtures.model_combo import ModelCombo
from tests.integration.pipelex.test_data import ImageGenTestCases
@@ -32,6 +33,7 @@ class TestImageGeneration:
pretty_print(f"Testing image generation with handle '{img_gen_combo.handle}', output format '{img_gen_job_params.output_format}'")
pretty_print(f"Positive text: {positive_text}\nNegative text: {negative_text}", title="Prompts")
img_gen_worker_async = get_img_gen_worker(img_gen_handle=img_gen_combo.handle)
+ skip_if_img_gen_params_unsupported(img_gen_worker_async.inference_model, img_gen_job_params)
img_gen_job = ImgGenJobFactory.make_img_gen_job_from_prompt_contents(
positive_text=positive_text,
negative_text=negative_text,
@@ -69,6 +71,7 @@ class TestImageGeneration:
background=Background.TRANSPARENT,
output_format=ImageFormat.PNG,
)
+ skip_if_img_gen_params_unsupported(img_gen_worker_async.inference_model, img_gen_job_params)
img_gen_job = ImgGenJobFactory.make_img_gen_job_from_prompt_contents(
positive_text=positive_text,
negative_text=negative_text,
@@ -100,6 +103,7 @@ class TestImageGeneration:
generated_content_factory: GeneratedContentFactory,
):
img_gen_worker_async = get_img_gen_worker(img_gen_handle=img_gen_combo.handle)
+ skip_if_img_gen_params_unsupported(img_gen_worker_async.inference_model, img_gen_job_params)
img_gen_job = ImgGenJobFactory.make_img_gen_job_from_prompt_contents(
positive_text=positive_text,
negative_text=negative_text,
diff --git a/tests/integration/pipelex/cogt/test_img_gen_param_support.py b/tests/integration/pipelex/cogt/test_img_gen_param_support.py
new file mode 100644
index 000000000..7335fe1e1
--- /dev/null
+++ b/tests/integration/pipelex/cogt/test_img_gen_param_support.py
@@ -0,0 +1,165 @@
+"""Integration tests for ImgGenParamSupport against the real loaded model deck.
+
+These run without contacting any inference API: they only read rules from the
+deck and verify the helper produces the expected accept/reject verdicts for
+parameter values that real users would reasonably try.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from pipelex.cogt.img_gen.img_gen_job_components import (
+ AspectRatio,
+ Background,
+ ImgGenJobParams,
+ InputFidelity,
+)
+from pipelex.cogt.img_gen.img_gen_param_support import ImgGenParamSupport
+from pipelex.cogt.model_backends.model_type import ModelType
+from pipelex.hub import get_model_deck
+from pipelex.tools.misc.image_utils import ImageFormat
+
+
+class TestImgGenParamSupportIntegration:
+ """Verifies ImgGenParamSupport against rules loaded from the real model deck."""
+
+ @pytest.mark.parametrize(
+ "model_handle",
+ ["gpt-image-1", "gpt-image-1-mini", "gpt-image-1.5"],
+ )
+ def test_legacy_openai_rejects_landscape_4_3(self, model_handle: str) -> None:
+ spec = get_model_deck().get_optional_inference_model(model_handle=model_handle, model_type=ModelType.IMG_GEN)
+ if spec is None or spec.rules is None:
+ pytest.skip(f"Model '{model_handle}' not in current deck")
+ check = ImgGenParamSupport.check_aspect_ratio(
+ rules=spec.rules,
+ aspect_ratio=AspectRatio.LANDSCAPE_4_3,
+ size=None,
+ model_name=spec.name,
+ )
+ assert check.is_supported is False
+ assert check.reason is not None
+ assert spec.name in check.reason
+
+ @pytest.mark.parametrize(
+ "model_handle",
+ ["gpt-image-1", "gpt-image-1-mini", "gpt-image-1.5"],
+ )
+ def test_legacy_openai_accepts_square(self, model_handle: str) -> None:
+ spec = get_model_deck().get_optional_inference_model(model_handle=model_handle, model_type=ModelType.IMG_GEN)
+ if spec is None or spec.rules is None:
+ pytest.skip(f"Model '{model_handle}' not in current deck")
+ check = ImgGenParamSupport.check_aspect_ratio(
+ rules=spec.rules,
+ aspect_ratio=AspectRatio.SQUARE,
+ size=None,
+ model_name=spec.name,
+ )
+ assert check.is_supported is True
+
+ def test_gpt_image_2_rejects_transparent_background(self) -> None:
+ spec = get_model_deck().get_optional_inference_model(model_handle="gpt-image-2", model_type=ModelType.IMG_GEN)
+ if spec is None or spec.rules is None:
+ pytest.skip("Model 'gpt-image-2' not in current deck")
+ check = ImgGenParamSupport.check_background(
+ rules=spec.rules,
+ background=Background.TRANSPARENT,
+ model_name=spec.name,
+ )
+ assert check.is_supported is False
+ assert check.reason is not None
+ assert "transparent" in check.reason.lower()
+
+ def test_gpt_image_2_rejects_explicit_input_fidelity(self) -> None:
+ spec = get_model_deck().get_optional_inference_model(model_handle="gpt-image-2", model_type=ModelType.IMG_GEN)
+ if spec is None or spec.rules is None:
+ pytest.skip("Model 'gpt-image-2' not in current deck")
+ check = ImgGenParamSupport.check_input_fidelity(
+ rules=spec.rules,
+ input_fidelity=InputFidelity.HIGH,
+ model_name=spec.name,
+ )
+ assert check.is_supported is False
+
+ @pytest.mark.parametrize(
+ "aspect_ratio",
+ [
+ AspectRatio.SQUARE,
+ AspectRatio.LANDSCAPE_4_3,
+ AspectRatio.LANDSCAPE_16_9,
+ AspectRatio.PORTRAIT_3_4,
+ AspectRatio.PORTRAIT_9_16,
+ ],
+ )
+ def test_gpt_image_2_supports_broader_aspect_ratios(self, aspect_ratio: AspectRatio) -> None:
+ spec = get_model_deck().get_optional_inference_model(model_handle="gpt-image-2", model_type=ModelType.IMG_GEN)
+ if spec is None or spec.rules is None:
+ pytest.skip("Model 'gpt-image-2' not in current deck")
+ check = ImgGenParamSupport.check_aspect_ratio(
+ rules=spec.rules,
+ aspect_ratio=aspect_ratio,
+ size=None,
+ model_name=spec.name,
+ )
+ assert check.is_supported is True
+
+ def test_check_job_params_legacy_openai_with_unsupported_combo(self) -> None:
+ """Reproduces the C.2 probe failure for img_gen_job_params2 (LANDSCAPE_4_3, JPEG)."""
+ spec = get_model_deck().get_optional_inference_model(model_handle="gpt-image-1", model_type=ModelType.IMG_GEN)
+ if spec is None or spec.rules is None:
+ pytest.skip("Model 'gpt-image-1' not in current deck")
+ params = ImgGenJobParams(
+ aspect_ratio=AspectRatio.LANDSCAPE_4_3,
+ background=Background.OPAQUE,
+ output_format=ImageFormat.JPEG,
+ )
+ reasons = ImgGenParamSupport.check_job_params(
+ rules=spec.rules,
+ params=params,
+ model_name=spec.name,
+ )
+ assert len(reasons) >= 1
+ assert any("landscape_4_3" in reason.lower() for reason in reasons)
+
+ def test_check_job_params_legacy_openai_with_supported_combo(self) -> None:
+ """Square + opaque + PNG should be supported by every legacy OpenAI img-gen model."""
+ spec = get_model_deck().get_optional_inference_model(model_handle="gpt-image-1", model_type=ModelType.IMG_GEN)
+ if spec is None or spec.rules is None:
+ pytest.skip("Model 'gpt-image-1' not in current deck")
+ params = ImgGenJobParams(
+ aspect_ratio=AspectRatio.SQUARE,
+ background=Background.OPAQUE,
+ output_format=ImageFormat.PNG,
+ )
+ reasons = ImgGenParamSupport.check_job_params(
+ rules=spec.rules,
+ params=params,
+ model_name=spec.name,
+ )
+ assert reasons == []
+
+ def test_every_img_gen_model_in_deck_accepts_some_aspect_ratio(self) -> None:
+ """Sanity check: every img_gen model in the deck should accept at least one aspect ratio.
+
+ Catches accidental rule mistakes that would mark every aspect ratio unsupported.
+ """
+ deck = get_model_deck()
+ img_gen_models = [
+ (handle, spec) for handle, spec in deck.inference_models.items() if spec.model_type == ModelType.IMG_GEN and spec.rules is not None
+ ]
+ assert img_gen_models, "Expected at least one img-gen model with rules in the deck"
+ for handle, spec in img_gen_models:
+ assert spec.rules is not None
+ supports_at_least_one = False
+ for aspect_ratio in AspectRatio:
+ check = ImgGenParamSupport.check_aspect_ratio(
+ rules=spec.rules,
+ aspect_ratio=aspect_ratio,
+ size=None,
+ model_name=spec.name,
+ )
+ if check.is_supported:
+ supports_at_least_one = True
+ break
+ assert supports_at_least_one, f"Model '{handle}' rejects every aspect ratio — likely a rules misconfiguration"
diff --git a/tests/integration/pipelex/fixtures/img_gen_fixtures.py b/tests/integration/pipelex/fixtures/img_gen_fixtures.py
index 45cb7dc44..7e30c1be7 100644
--- a/tests/integration/pipelex/fixtures/img_gen_fixtures.py
+++ b/tests/integration/pipelex/fixtures/img_gen_fixtures.py
@@ -3,7 +3,28 @@
import pytest
from pipelex.cogt.img_gen.img_gen_job_components import AspectRatio, Background, ImgGenJobParams, Quality
-from pipelex.tools.misc.image_utils import ImageFormat
+from pipelex.cogt.img_gen.img_gen_param_support import ImgGenParamSupport
+from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
+
+
+def skip_if_img_gen_params_unsupported(
+ inference_model: InferenceModelSpec,
+ params: ImgGenJobParams,
+ *,
+ has_input_images: bool = False,
+) -> None:
+ """Call from tests: pytest.skip if any param value isn't supported by the model's rules."""
+ if inference_model.rules is None:
+ return
+ reasons = ImgGenParamSupport.check_job_params(
+ rules=inference_model.rules,
+ params=params,
+ model_name=inference_model.name,
+ has_input_images=has_input_images,
+ )
+ if reasons:
+ pytest.skip(f"Model '{inference_model.name}' does not support: {'; '.join(reasons)}")
+
# ================================================================================================
# Image generation model collections are now defined in .pipelex-dev/test_profiles.toml
@@ -13,36 +34,36 @@ from pipelex.tools.misc.image_utils import ImageFormat
@pytest.fixture(
params=[
+ # ImgGenJobParams(
+ # aspect_ratio=AspectRatio.SQUARE,
+ # background=Background.OPAQUE,
+ # nb_steps=8,
+ # guidance_scale=2.5,
+ # is_moderated=None,
+ # safety_tolerance=1,
+ # is_raw=None,
+ # output_format=ImageFormat.PNG,
+ # ),
ImgGenJobParams(
aspect_ratio=AspectRatio.SQUARE,
background=Background.OPAQUE,
- nb_steps=8,
- guidance_scale=2.5,
- is_moderated=None,
- safety_tolerance=1,
- is_raw=None,
- output_format=ImageFormat.PNG,
- ),
- ImgGenJobParams(
- aspect_ratio=AspectRatio.PORTRAIT_9_16,
- background=Background.OPAQUE,
- quality=Quality.MEDIUM,
- guidance_scale=2.5,
- is_moderated=None,
- safety_tolerance=1,
- is_raw=None,
- output_format=ImageFormat.PNG,
- ),
- ImgGenJobParams(
- aspect_ratio=AspectRatio.LANDSCAPE_4_3,
- background=Background.OPAQUE,
- quality=Quality.HIGH,
- guidance_scale=2.5,
+ quality=Quality.LOW,
+ guidance_scale=None,
is_moderated=None,
- safety_tolerance=1,
+ safety_tolerance=None,
is_raw=None,
- output_format=ImageFormat.JPEG,
+ output_format=None,
),
+ # ImgGenJobParams(
+ # aspect_ratio=AspectRatio.LANDSCAPE_4_3,
+ # background=Background.OPAQUE,
+ # quality=Quality.HIGH,
+ # guidance_scale=2.5,
+ # is_moderated=None,
+ # safety_tolerance=1,
+ # is_raw=None,
+ # output_format=ImageFormat.JPEG,
+ # ),
],
)
def img_gen_job_params(request: pytest.FixtureRequest) -> ImgGenJobParams:
diff --git a/tests/integration/pipelex/pipes/operator/pipe_img_gen/test_pipe_img_gen_blueprint_validation.py b/tests/integration/pipelex/pipes/operator/pipe_img_gen/test_pipe_img_gen_blueprint_validation.py
new file mode 100644
index 000000000..6be29b4ff
--- /dev/null
+++ b/tests/integration/pipelex/pipes/operator/pipe_img_gen/test_pipe_img_gen_blueprint_validation.py
@@ -0,0 +1,204 @@
+"""Integration tests for PipeImgGen.validate_inputs_static parameter-support check.
+
+Verifies that constructing a PipeImgGen with a model handle and an
+explicit parameter value the model's rules don't accept raises a
+PipeValidationError at static-validation time (i.e. as soon as the
+blueprint is converted to a pipe — before any inference runs).
+
+These tests use a routing-override fixture to ensure model handles
+resolve to backends with up-to-date rules (the openai backend), not to
+backends whose rules predate the current taxonomy enums.
+"""
+
+from __future__ import annotations
+
+import shutil
+import tempfile
+from pathlib import Path
+from typing import Callable, Iterator
+
+import pytest
+from pydantic import ValidationError
+from pytest import MonkeyPatch
+
+from pipelex.cogt.img_gen.img_gen_job_components import AspectRatio, Background
+from pipelex.cogt.model_backends.model_type import ModelType
+from pipelex.core.concepts.native.concept_native import NativeConceptCode
+from pipelex.core.pipes.exceptions import PipeValidationError
+from pipelex.core.pipes.pipe_factory import PipeFactory
+from pipelex.hub import get_console, get_model_deck
+from pipelex.pipe_operators.img_gen.pipe_img_gen import PipeImgGen
+from pipelex.pipe_operators.img_gen.pipe_img_gen_blueprint import PipeImgGenBlueprint
+from pipelex.pipelex import Pipelex
+from pipelex.system.configuration.config_loader import config_manager
+from pipelex.system.runtime import IntegrationMode, runtime_manager
+from pipelex.tools.misc.toml_utils import load_toml_with_tomlkit, save_toml_to_path
+
+
[email protected](scope="class")
+def pipelex_routed_to_openai() -> Iterator[None]:
+ """Reload Pipelex with routing forced to the openai backend so img-gen rules
+ come from the openai TOML (current taxonomies) rather than the gateway one.
+ """
+ Pipelex.teardown_if_needed()
+
+ routing_profile_name = "all_openai"
+ routing_monkeypatch = MonkeyPatch()
+ routing_profiles_path = Path(config_manager.routing_profiles_file_path)
+ routing_profiles_doc = load_toml_with_tomlkit(str(routing_profiles_path))
+ routing_profiles_doc["active"] = routing_profile_name
+ routing_override_dir = Path(tempfile.mkdtemp(prefix="pipelex-routing-pipe-img-gen-validation-"))
+ routing_override_path = routing_override_dir / routing_profiles_path.name
+ save_toml_to_path(routing_profiles_doc, str(routing_override_path))
+ routing_monkeypatch.setattr(
+ type(config_manager),
+ "routing_profiles_file_path",
+ property(lambda _self: str(routing_override_path)),
+ )
+ get_console().print("[cyan]Routing to backend:[/cyan] openai (for blueprint-validation test)")
+
+ try:
+ integration_mode = IntegrationMode.CI if runtime_manager.is_ci_testing else IntegrationMode.PYTEST
+ Pipelex.make(integration_mode=integration_mode)
+ except Exception:
+ routing_monkeypatch.undo()
+ shutil.rmtree(routing_override_dir, ignore_errors=True)
+ raise
+
+ yield
+
+ Pipelex.teardown_if_needed()
+ routing_monkeypatch.undo()
+ shutil.rmtree(routing_override_dir, ignore_errors=True)
+
+
[email protected]("pipelex_routed_to_openai")
+class TestPipeImgGenBlueprintValidation:
+ """End-to-blueprint-load validation of PipeImgGen parameters against model rules."""
+
+ def test_legacy_model_with_unsupported_aspect_ratio_raises(
+ self,
+ load_empty_library: Callable[[], str],
+ ) -> None:
+ """gpt-image-1 doesn't support landscape_4_3 — building the pipe must raise PipeValidationError."""
+ load_empty_library()
+ spec = get_model_deck().get_optional_inference_model(model_handle="gpt-image-1", model_type=ModelType.IMG_GEN)
+ if spec is None or spec.rules is None:
+ pytest.skip("gpt-image-1 not available in current deck routing")
+
+ blueprint = PipeImgGenBlueprint(
+ description="Bad config: legacy model + landscape_4_3",
+ model="gpt-image-1",
+ output=NativeConceptCode.IMAGE,
+ prompt="A test prompt",
+ aspect_ratio=AspectRatio.LANDSCAPE_4_3,
+ )
+
+ with pytest.raises((PipeValidationError, ValidationError)) as exc_info:
+ PipeFactory[PipeImgGen].make_from_blueprint(
+ domain_code="test_domain",
+ pipe_code="bad_pipe_landscape_4_3",
+ blueprint=blueprint,
+ )
+
+ msg = str(exc_info.value)
+ assert "gpt-image-1" in msg
+ assert "landscape_4_3" in msg.lower()
+
+ def test_legacy_model_with_supported_aspect_ratio_succeeds(
+ self,
+ load_empty_library: Callable[[], str],
+ ) -> None:
+ """Same model with a supported aspect ratio (square) must build cleanly."""
+ load_empty_library()
+ spec = get_model_deck().get_optional_inference_model(model_handle="gpt-image-1", model_type=ModelType.IMG_GEN)
+ if spec is None or spec.rules is None:
+ pytest.skip("gpt-image-1 not available in current deck routing")
+
+ blueprint = PipeImgGenBlueprint(
+ description="Good config: legacy model + square",
+ model="gpt-image-1",
+ output=NativeConceptCode.IMAGE,
+ prompt="A test prompt",
+ aspect_ratio=AspectRatio.SQUARE,
+ )
+
+ pipe = PipeFactory[PipeImgGen].make_from_blueprint(
+ domain_code="test_domain",
+ pipe_code="good_pipe_square",
+ blueprint=blueprint,
+ )
+ assert isinstance(pipe, PipeImgGen)
+
+ def test_gpt_image_2_with_transparent_background_raises(
+ self,
+ load_empty_library: Callable[[], str],
+ ) -> None:
+ """gpt-image-2 has BackgroundTaxonomy.UNAVAILABLE — transparent must be rejected."""
+ load_empty_library()
+ spec = get_model_deck().get_optional_inference_model(model_handle="gpt-image-2", model_type=ModelType.IMG_GEN)
+ if spec is None or spec.rules is None:
+ pytest.skip("gpt-image-2 not available in current deck routing")
+
+ blueprint = PipeImgGenBlueprint(
+ description="Bad config: gpt-image-2 + transparent",
+ model="gpt-image-2",
+ output=NativeConceptCode.IMAGE,
+ prompt="A test prompt",
+ background=Background.TRANSPARENT,
+ )
+
+ with pytest.raises((PipeValidationError, ValidationError)) as exc_info:
+ PipeFactory[PipeImgGen].make_from_blueprint(
+ domain_code="test_domain",
+ pipe_code="bad_pipe_gpt_image_2_transparent",
+ blueprint=blueprint,
+ )
+
+ msg = str(exc_info.value).lower()
+ assert "gpt-image-2" in msg
+ assert "transparent" in msg
+
+ def test_blueprint_with_no_explicit_params_does_not_raise(
+ self,
+ load_empty_library: Callable[[], str],
+ ) -> None:
+ """If the blueprint defers all params to deck defaults, no early validation should fire."""
+ load_empty_library()
+ spec = get_model_deck().get_optional_inference_model(model_handle="gpt-image-1", model_type=ModelType.IMG_GEN)
+ if spec is None or spec.rules is None:
+ pytest.skip("gpt-image-1 not available in current deck routing")
+
+ blueprint = PipeImgGenBlueprint(
+ description="Defers all params to deck defaults",
+ model="gpt-image-1",
+ output=NativeConceptCode.IMAGE,
+ prompt="A test prompt",
+ )
+
+ pipe = PipeFactory[PipeImgGen].make_from_blueprint(
+ domain_code="test_domain",
+ pipe_code="defaults_pipe",
+ blueprint=blueprint,
+ )
+ assert isinstance(pipe, PipeImgGen)
+
+ def test_blueprint_without_model_choice_does_not_raise(
+ self,
+ load_empty_library: Callable[[], str],
+ ) -> None:
+ """If the blueprint has no `model` choice, validation is skipped (deck default applies later)."""
+ load_empty_library()
+ blueprint = PipeImgGenBlueprint(
+ description="No model choice — uses deck default",
+ output=NativeConceptCode.IMAGE,
+ prompt="A test prompt",
+ aspect_ratio=AspectRatio.LANDSCAPE_4_3, # would be unsupported on legacy, but no model is bound here
+ )
+
+ pipe = PipeFactory[PipeImgGen].make_from_blueprint(
+ domain_code="test_domain",
+ pipe_code="no_model_pipe",
+ blueprint=blueprint,
+ )
+ assert isinstance(pipe, PipeImgGen)
diff --git a/tests/integration/pipelex/test_data.py b/tests/integration/pipelex/test_data.py
index fc8eeac40..08fe32e29 100644
--- a/tests/integration/pipelex/test_data.py
+++ b/tests/integration/pipelex/test_data.py
@@ -166,7 +166,7 @@ class ImageGenTestCases:
IMAGE_GEN_PROMPT_CONTENTS: ClassVar[list[tuple[str, str, str | None]]] = [ # topic, positive_text, negative_text
# ("dog wearing sunglasses", "a dog wearing sunglasses", "blue sky"),
# ("otter playing poker", "an otter playing poker", None),
- ("coding woman with dragon tatoo", "a woman with a dragon tatoo, wearing a tank top, coding in python", "nude"),
+ ("coding woman with dragon tatoo", "a woman with a dragon tatoo, wearing a tank top, coding in python", None),
]
diff --git a/tests/unit/pipelex/cogt/img_gen/test_img_gen_args_factory.py b/tests/unit/pipelex/cogt/img_gen/test_img_gen_args_factory.py
index 8c7adb7ea..311b97475 100644
--- a/tests/unit/pipelex/cogt/img_gen/test_img_gen_args_factory.py
+++ b/tests/unit/pipelex/cogt/img_gen/test_img_gen_args_factory.py
@@ -8,9 +8,11 @@ from __future__ import annotations
from typing import TYPE_CHECKING, cast
+import openai
import pytest
from pipelex.cogt.exceptions import ImgGenParameterError
+from pipelex.cogt.image.image_size import ImageSize
from pipelex.cogt.image.prompt_image import PromptImage, PromptImageUri
from pipelex.cogt.img_gen.img_gen_args_factory import ImgGenArgsFactory
from pipelex.cogt.img_gen.img_gen_job import ImgGenJob
@@ -20,15 +22,33 @@ from pipelex.cogt.img_gen.img_gen_job_components import (
ImgGenJobConfig,
ImgGenJobParams,
ImgGenJobReport,
+ InputFidelity,
+ Quality,
)
from pipelex.cogt.img_gen.img_gen_model_rules import (
+ AspectRatioTaxonomy,
+ BackgroundTaxonomy,
ImgGenArgTopic,
ImgGenModelRules,
+ InferenceTaxonomy,
+ InputFidelityTaxonomy,
InputImagesTaxonomy,
+ ModelChoiceTaxonomy,
+ NumImagesTaxonomy,
+ OutputCompressionTaxonomy,
+ OutputFormatTaxonomy,
+ PromptTaxonomy,
+ SafetyCheckerTaxonomy,
)
from pipelex.cogt.img_gen.img_gen_prompt import ImgGenPrompt
+from pipelex.cogt.llm.thinking_mode import ThinkingMode
+from pipelex.cogt.model_backends.model_spec import InferenceModelSpec
+from pipelex.cogt.model_backends.model_type import ModelType
+from pipelex.cogt.usage.cost_category import CostCategory
from pipelex.pipeline.job_metadata import JobMetadata
+from pipelex.plugins.openai.openai_img_gen_worker import OpenAIImgGenWorker
from pipelex.tools.misc.filetype_utils import FileType
+from pipelex.tools.misc.image_utils import ImageFormat
from pipelex.tools.uri.prepared_file import PreparedFileBase64
if TYPE_CHECKING:
@@ -39,7 +59,13 @@ class TestImgGenArgsFactory:
"""Tests for ImgGenArgsFactory.make_args_for_model validation of input images."""
@staticmethod
- def _make_test_job(input_images: list[PromptImage] | None = None) -> ImgGenJob:
+ def _make_test_job(
+ input_images: list[PromptImage] | None = None,
+ aspect_ratio: AspectRatio = AspectRatio.SQUARE,
+ size: ImageSize | None = None,
+ input_fidelity: InputFidelity | None = None,
+ output_format: ImageFormat | None = ImageFormat.PNG,
+ ) -> ImgGenJob:
"""Create a test ImgGenJob with optional input images."""
return ImgGenJob(
img_gen_prompt=ImgGenPrompt(
@@ -47,8 +73,11 @@ class TestImgGenArgsFactory:
input_images=input_images,
),
job_params=ImgGenJobParams(
- aspect_ratio=AspectRatio.SQUARE,
+ aspect_ratio=aspect_ratio,
+ size=size,
background=Background.OPAQUE,
+ input_fidelity=input_fidelity,
+ output_format=output_format,
),
job_config=ImgGenJobConfig(is_sync_mode=False),
job_report=ImgGenJobReport(),
@@ -88,6 +117,7 @@ class TestImgGenArgsFactory:
img_gen_job=job,
nb_images=1,
model_id="test-model",
+ model_name="test-model",
)
error_message = str(exc_info.value)
@@ -119,6 +149,7 @@ class TestImgGenArgsFactory:
img_gen_job=job,
nb_images=1,
model_id="test-model",
+ model_name="test-model",
)
assert isinstance(result, dict)
@@ -139,6 +170,7 @@ class TestImgGenArgsFactory:
img_gen_job=job,
nb_images=1,
model_id="test-model",
+ model_name="test-model",
)
assert isinstance(result, dict)
@@ -158,6 +190,346 @@ class TestImgGenArgsFactory:
img_gen_job=job,
nb_images=1,
model_id="test-model",
+ model_name="test-model",
)
assert isinstance(result, dict)
+
+ @staticmethod
+ def _make_gpt_image_2_rules() -> ImgGenModelRules:
+ return {
+ ImgGenArgTopic.MODEL_CHOICE: ModelChoiceTaxonomy.MODEL_ID,
+ ImgGenArgTopic.PROMPT: PromptTaxonomy.POSITIVE_ONLY,
+ ImgGenArgTopic.NUM_IMAGES: NumImagesTaxonomy.GPT_IMAGE,
+ ImgGenArgTopic.ASPECT_RATIO: AspectRatioTaxonomy.GPT_IMAGE_2,
+ ImgGenArgTopic.BACKGROUND: BackgroundTaxonomy.UNAVAILABLE,
+ ImgGenArgTopic.INFERENCE: InferenceTaxonomy.GPT_IMAGE,
+ ImgGenArgTopic.SAFETY_CHECKER: SafetyCheckerTaxonomy.UNAVAILABLE,
+ ImgGenArgTopic.OUTPUT_FORMAT: OutputFormatTaxonomy.UNAVAILABLE,
+ ImgGenArgTopic.INPUT_IMAGES: InputImagesTaxonomy.GPT_IMAGE,
+ ImgGenArgTopic.INPUT_FIDELITY: InputFidelityTaxonomy.UNAVAILABLE,
+ }
+
+ @staticmethod
+ def _make_legacy_openai_rules() -> ImgGenModelRules:
+ return {
+ ImgGenArgTopic.PROMPT: PromptTaxonomy.POSITIVE_ONLY,
+ ImgGenArgTopic.NUM_IMAGES: NumImagesTaxonomy.GPT_IMAGE,
+ ImgGenArgTopic.ASPECT_RATIO: AspectRatioTaxonomy.GPT_IMAGE_LEGACY,
+ ImgGenArgTopic.BACKGROUND: BackgroundTaxonomy.AVAILABLE,
+ ImgGenArgTopic.INFERENCE: InferenceTaxonomy.GPT_IMAGE,
+ ImgGenArgTopic.SAFETY_CHECKER: SafetyCheckerTaxonomy.OPENAI_MODERATION,
+ ImgGenArgTopic.OUTPUT_FORMAT: OutputFormatTaxonomy.GPT_IMAGE_LEGACY,
+ ImgGenArgTopic.INPUT_FIDELITY: InputFidelityTaxonomy.GPT_IMAGE_LEGACY,
+ }
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "size",
+ [
+ ImageSize(width=1024, height=1024),
+ ImageSize(width=1024, height=1536),
+ ImageSize(width=1536, height=1024),
+ ImageSize(width=2560, height=1440),
+ ImageSize(width=3824, height=2144),
+ ],
+ )
+ async def test_gpt_image_2_accepts_valid_exact_sizes(self, size: ImageSize) -> None:
+ result = await ImgGenArgsFactory.make_args_for_model(
+ model_rules=self._make_gpt_image_2_rules(),
+ img_gen_job=self._make_test_job(size=size),
+ nb_images=1,
+ model_id="gpt-image-2",
+ model_name="gpt-image-2",
+ )
+
+ assert result["size"] == f"{size.width}x{size.height}"
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("size", "expected_error"),
+ [
+ (ImageSize(width=1025, height=1024), "multiples of 16"),
+ (ImageSize(width=3840, height=2160), "less than 3840"),
+ (ImageSize(width=3072, height=1008), "at most 3:1"),
+ (ImageSize(width=800, height=800), "at least 655360"),
+ (ImageSize(width=3824, height=2176), "at most 8294400"),
+ ],
+ )
+ async def test_gpt_image_2_rejects_invalid_exact_sizes(self, size: ImageSize, expected_error: str) -> None:
+ with pytest.raises(ImgGenParameterError) as exc_info:
+ await ImgGenArgsFactory.make_args_for_model(
+ model_rules=self._make_gpt_image_2_rules(),
+ img_gen_job=self._make_test_job(size=size),
+ nb_images=1,
+ model_id="gpt-image-2",
+ model_name="gpt-image-2",
+ )
+
+ assert expected_error in str(exc_info.value)
+
+ @pytest.mark.asyncio
+ async def test_gpt_image_2_rejects_explicit_input_fidelity(self) -> None:
+ with pytest.raises(ImgGenParameterError) as exc_info:
+ await ImgGenArgsFactory.make_args_for_model(
+ model_rules=self._make_gpt_image_2_rules(),
+ img_gen_job=self._make_test_job(input_fidelity=InputFidelity.HIGH),
+ nb_images=1,
+ model_id="gpt-image-2",
+ model_name="gpt-image-2",
+ )
+
+ error_message = str(exc_info.value)
+ assert "gpt-image-2" in error_message
+ assert "does not support input_fidelity" in error_message
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("aspect_ratio", "expected_size"),
+ [
+ (AspectRatio.SQUARE, "1024x1024"),
+ (AspectRatio.LANDSCAPE_3_2, "1536x1024"),
+ (AspectRatio.PORTRAIT_2_3, "1024x1536"),
+ ],
+ )
+ async def test_legacy_openai_models_map_supported_aspect_ratios(self, aspect_ratio: AspectRatio, expected_size: str) -> None:
+ result = await ImgGenArgsFactory.make_args_for_model(
+ model_rules=self._make_legacy_openai_rules(),
+ img_gen_job=self._make_test_job(aspect_ratio=aspect_ratio),
+ nb_images=1,
+ model_id="gpt-image-1",
+ model_name="gpt-image-1",
+ )
+
+ assert result["size"] == expected_size
+
+ @pytest.mark.asyncio
+ async def test_legacy_openai_models_use_explicit_size_before_aspect_ratio(self) -> None:
+ result = await ImgGenArgsFactory.make_args_for_model(
+ model_rules=self._make_legacy_openai_rules(),
+ img_gen_job=self._make_test_job(
+ aspect_ratio=AspectRatio.SQUARE,
+ size=ImageSize(width=1536, height=1024),
+ ),
+ nb_images=1,
+ model_id="gpt-image-1.5",
+ model_name="gpt-image-1.5",
+ )
+
+ assert result["size"] == "1536x1024"
+
+ @pytest.mark.asyncio
+ async def test_legacy_openai_models_reject_unsupported_aspect_ratio_with_model_name(self) -> None:
+ with pytest.raises(ImgGenParameterError) as exc_info:
+ await ImgGenArgsFactory.make_args_for_model(
+ model_rules=self._make_legacy_openai_rules(),
+ img_gen_job=self._make_test_job(aspect_ratio=AspectRatio.LANDSCAPE_4_3),
+ nb_images=1,
+ model_id="azure-gpt-image-1-mini-deployment",
+ model_name="gpt-image-1-mini",
+ )
+
+ error_message = str(exc_info.value)
+ assert "gpt-image-1-mini" in error_message
+ assert "azure-gpt-image-1-mini-deployment" not in error_message
+ assert "OpenAI image model" in error_message
+ assert "GPT Image 1" not in error_message
+
+ def test_make_args_from_output_compression_gpt_image_emits_100(self) -> None:
+ """Legacy gpt-image rules emit `output_compression = 100` (max quality for JPEG/WEBP, no-op for PNG)."""
+ result = ImgGenArgsFactory.make_args_from_output_compression(
+ output_compression_taxonomy=OutputCompressionTaxonomy.GPT_IMAGE_LEGACY,
+ )
+
+ assert result == {"output_compression": 100}
+
+ def test_make_args_from_output_compression_unavailable_emits_nothing(self) -> None:
+ """Models without `output_compression` support skip the kwarg entirely."""
+ result = ImgGenArgsFactory.make_args_from_output_compression(
+ output_compression_taxonomy=OutputCompressionTaxonomy.UNAVAILABLE,
+ )
+
+ assert result == {}
+ assert "output_compression" not in result
+
+ def test_make_args_from_model_name_can_emit_pipelex_model_name(self) -> None:
+ """Some gateway-style APIs expect the Pipelex model name rather than the backend model id."""
+ result = ImgGenArgsFactory.make_args_from_model_name(
+ model_name_taxonomy=ModelChoiceTaxonomy.MODEL_NAME,
+ model_id="provider-deployment-id",
+ model_name="pipelex-model-name",
+ )
+
+ assert result == {"model": "pipelex-model-name"}
+
+ @pytest.mark.parametrize(
+ "output_format_taxonomy",
+ [
+ OutputFormatTaxonomy.SDXL,
+ OutputFormatTaxonomy.FLUX_1,
+ OutputFormatTaxonomy.FLUX_2,
+ OutputFormatTaxonomy.GPT_IMAGE_LEGACY,
+ OutputFormatTaxonomy.UNAVAILABLE,
+ ],
+ )
+ def test_make_args_from_output_format_returns_empty_when_none(self, output_format_taxonomy: OutputFormatTaxonomy) -> None:
+ """When output_format is None, every taxonomy returns an empty dict so the provider applies its own default."""
+ result = ImgGenArgsFactory.make_args_from_output_format(
+ output_format_taxonomy=output_format_taxonomy,
+ output_format=None,
+ )
+
+ assert result == {}
+ assert "format" not in result
+ assert "output_format" not in result
+
+ @pytest.mark.asyncio
+ async def test_gpt_inference_taxonomy_defaults_quality_to_medium(self) -> None:
+ """When job_params.quality is None and inference taxonomy is GPT, quality defaults to 'medium'."""
+ job = self._make_test_job()
+ # Ensure no explicit quality on the job
+ job.job_params.quality = None
+ result = await ImgGenArgsFactory.make_args_for_model(
+ model_rules=self._make_gpt_image_2_rules(),
+ img_gen_job=job,
+ nb_images=1,
+ model_id="gpt-image-2",
+ model_name="gpt-image-2",
+ )
+
+ assert result["quality"] == "medium"
+
+ @pytest.mark.asyncio
+ async def test_openai_direct_worker_uses_rule_generated_args(self, mocker: MockerFixture) -> None:
+ openai_client = openai.AsyncOpenAI(api_key="sk-test")
+
+ class FakeImageData:
+ b64_json = "dGVzdA=="
+
+ class FakeUsage:
+ input_tokens = 1
+ output_tokens = 2
+
+ class FakeImagesResponse:
+ def __init__(self) -> None:
+ self.data = [FakeImageData()]
+ self.output_format = "png"
+ self.size = None
+ self.usage = FakeUsage()
+
+ generate_mock = mocker.AsyncMock(return_value=FakeImagesResponse())
+ mocker.patch.object(openai_client.images, "generate", generate_mock)
+
+ inference_model = InferenceModelSpec(
+ backend_name="openai",
+ name="gpt-image-2",
+ sdk="openai_img_gen",
+ model_type=ModelType.IMG_GEN,
+ model_id="gpt-image-2",
+ inputs=["text", "images"],
+ outputs=["image"],
+ costs={CostCategory.INPUT: 8, CostCategory.OUTPUT: 30},
+ thinking_mode=ThinkingMode.NONE,
+ max_tokens=None,
+ max_prompt_images=None,
+ rules=self._make_gpt_image_2_rules(),
+ )
+ worker = OpenAIImgGenWorker(
+ sdk_instance=openai_client,
+ inference_model=inference_model,
+ )
+
+ job = self._make_test_job(size=ImageSize(width=2560, height=1440))
+ job.job_params.quality = Quality.HIGH
+ generated_images = await worker.gen_image_list(img_gen_job=job, nb_images=2)
+
+ generate_mock.assert_awaited_once()
+ assert generate_mock.await_args is not None
+ kwargs = generate_mock.await_args.kwargs
+ assert kwargs["model"] == "gpt-image-2"
+ assert kwargs["prompt"] == "A test prompt"
+ assert kwargs["n"] == 2
+ assert kwargs["size"] == "2560x1440"
+ assert kwargs["quality"] == "high"
+ assert "output_format" not in kwargs
+ assert "background" not in kwargs
+ assert generated_images[0].size == ImageSize(width=2560, height=1440)
+
+ @pytest.mark.asyncio
+ async def test_openai_edit_endpoint_strips_moderation_kwarg(self, mocker: MockerFixture) -> None:
+ """When routing to images.edit (input_images present), the 'moderation' kwarg is dropped to match the SDK signature."""
+ openai_client = openai.AsyncOpenAI(api_key="sk-test")
+
+ class FakeImageData:
+ b64_json = "dGVzdA=="
+
+ class FakeUsage:
+ input_tokens = 1
+ output_tokens = 2
+
+ class FakeImagesResponse:
+ def __init__(self) -> None:
+ self.data = [FakeImageData()]
+ self.output_format = "png"
+ self.size = "1024x1024"
+ self.usage = FakeUsage()
+
+ edit_mock = mocker.AsyncMock(return_value=FakeImagesResponse())
+ generate_mock = mocker.AsyncMock(return_value=FakeImagesResponse())
+ mocker.patch.object(openai_client.images, "edit", edit_mock)
+ mocker.patch.object(openai_client.images, "generate", generate_mock)
+
+ # Mock prep_prompt_images to avoid network calls
+ mock_prepped = [
+ PreparedFileBase64(
+ base64_data="iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
+ file_type=FileType(extension="png", mime="image/png"),
+ )
+ ]
+ mocker.patch(
+ "pipelex.cogt.img_gen.img_gen_args_factory.prep_prompt_images",
+ new_callable=mocker.AsyncMock,
+ return_value=mock_prepped,
+ )
+
+ inference_model = InferenceModelSpec(
+ backend_name="openai",
+ name="gpt-image-1",
+ sdk="openai_img_gen",
+ model_type=ModelType.IMG_GEN,
+ model_id="gpt-image-1",
+ inputs=["text", "images"],
+ outputs=["image"],
+ costs={CostCategory.INPUT: 10, CostCategory.OUTPUT: 40},
+ thinking_mode=ThinkingMode.NONE,
+ max_tokens=None,
+ max_prompt_images=None,
+ rules={
+ ImgGenArgTopic.MODEL_CHOICE: ModelChoiceTaxonomy.MODEL_ID,
+ ImgGenArgTopic.PROMPT: PromptTaxonomy.POSITIVE_ONLY,
+ ImgGenArgTopic.NUM_IMAGES: NumImagesTaxonomy.GPT_IMAGE,
+ ImgGenArgTopic.ASPECT_RATIO: AspectRatioTaxonomy.GPT_IMAGE_LEGACY,
+ ImgGenArgTopic.BACKGROUND: BackgroundTaxonomy.AVAILABLE,
+ ImgGenArgTopic.INFERENCE: InferenceTaxonomy.GPT_IMAGE,
+ ImgGenArgTopic.SAFETY_CHECKER: SafetyCheckerTaxonomy.OPENAI_MODERATION,
+ ImgGenArgTopic.OUTPUT_FORMAT: OutputFormatTaxonomy.GPT_IMAGE_LEGACY,
+ ImgGenArgTopic.INPUT_IMAGES: InputImagesTaxonomy.GPT_IMAGE,
+ ImgGenArgTopic.INPUT_FIDELITY: InputFidelityTaxonomy.GPT_IMAGE_LEGACY,
+ },
+ )
+ worker = OpenAIImgGenWorker(
+ sdk_instance=openai_client,
+ inference_model=inference_model,
+ )
+
+ input_images = cast("list[PromptImage]", [PromptImageUri(uri="https://example.com/image.png")])
+ job = self._make_test_job(input_images=input_images)
+ job.job_params.is_moderated = True
+
+ await worker.gen_image_list(img_gen_job=job, nb_images=1)
+
+ edit_mock.assert_awaited_once()
+ generate_mock.assert_not_awaited()
+ assert edit_mock.await_args is not None
+ kwargs = edit_mock.await_args.kwargs
+ assert "moderation" not in kwargs
diff --git a/tests/unit/pipelex/cogt/img_gen/test_img_gen_param_support.py b/tests/unit/pipelex/cogt/img_gen/test_img_gen_param_support.py
new file mode 100644
index 000000000..7d4211f02
--- /dev/null
+++ b/tests/unit/pipelex/cogt/img_gen/test_img_gen_param_support.py
@@ -0,0 +1,301 @@
+"""Unit tests for ImgGenParamSupport — capability checks against synthetic rules dicts."""
+
+from __future__ import annotations
+
+import pytest
+
+from pipelex.cogt.image.image_size import ImageSize
+from pipelex.cogt.img_gen.img_gen_job_components import (
+ AspectRatio,
+ Background,
+ ImgGenJobParams,
+ InputFidelity,
+)
+from pipelex.cogt.img_gen.img_gen_model_rules import (
+ AspectRatioTaxonomy,
+ BackgroundTaxonomy,
+ ImgGenArgTopic,
+ ImgGenModelRules,
+ InferenceTaxonomy,
+ InputFidelityTaxonomy,
+ InputImagesTaxonomy,
+ ModelChoiceTaxonomy,
+ NumImagesTaxonomy,
+ OutputFormatTaxonomy,
+ PromptTaxonomy,
+ SafetyCheckerTaxonomy,
+)
+from pipelex.cogt.img_gen.img_gen_param_support import ImgGenParamSupport, SupportCheck
+from pipelex.tools.misc.image_utils import ImageFormat
+
+
+def _make_legacy_openai_rules() -> ImgGenModelRules:
+ """Rules matching gpt-image-1 / gpt-image-1-mini / gpt-image-1.5."""
+ return {
+ ImgGenArgTopic.MODEL_CHOICE: ModelChoiceTaxonomy.MODEL_ID,
+ ImgGenArgTopic.PROMPT: PromptTaxonomy.POSITIVE_ONLY,
+ ImgGenArgTopic.NUM_IMAGES: NumImagesTaxonomy.GPT_IMAGE,
+ ImgGenArgTopic.ASPECT_RATIO: AspectRatioTaxonomy.GPT_IMAGE_LEGACY,
+ ImgGenArgTopic.BACKGROUND: BackgroundTaxonomy.AVAILABLE,
+ ImgGenArgTopic.INFERENCE: InferenceTaxonomy.GPT_IMAGE,
+ ImgGenArgTopic.SAFETY_CHECKER: SafetyCheckerTaxonomy.OPENAI_MODERATION,
+ ImgGenArgTopic.OUTPUT_FORMAT: OutputFormatTaxonomy.GPT_IMAGE_LEGACY,
+ ImgGenArgTopic.INPUT_IMAGES: InputImagesTaxonomy.GPT_IMAGE,
+ ImgGenArgTopic.INPUT_FIDELITY: InputFidelityTaxonomy.GPT_IMAGE_LEGACY,
+ }
+
+
+def _make_gpt_image_2_rules() -> ImgGenModelRules:
+ """Rules matching gpt-image-2."""
+ return {
+ ImgGenArgTopic.MODEL_CHOICE: ModelChoiceTaxonomy.MODEL_ID,
+ ImgGenArgTopic.PROMPT: PromptTaxonomy.POSITIVE_ONLY,
+ ImgGenArgTopic.NUM_IMAGES: NumImagesTaxonomy.GPT_IMAGE,
+ ImgGenArgTopic.ASPECT_RATIO: AspectRatioTaxonomy.GPT_IMAGE_2,
+ ImgGenArgTopic.BACKGROUND: BackgroundTaxonomy.UNAVAILABLE,
+ ImgGenArgTopic.INFERENCE: InferenceTaxonomy.GPT_IMAGE,
+ ImgGenArgTopic.SAFETY_CHECKER: SafetyCheckerTaxonomy.UNAVAILABLE,
+ ImgGenArgTopic.OUTPUT_FORMAT: OutputFormatTaxonomy.UNAVAILABLE,
+ ImgGenArgTopic.INPUT_IMAGES: InputImagesTaxonomy.GPT_IMAGE,
+ ImgGenArgTopic.INPUT_FIDELITY: InputFidelityTaxonomy.UNAVAILABLE,
+ }
+
+
+def _make_sdxl_rules() -> ImgGenModelRules:
+ """Rules matching SDXL family — uses different output_format taxonomy that rejects WEBP."""
+ return {
+ ImgGenArgTopic.PROMPT: PromptTaxonomy.WITH_NEGATIVE,
+ ImgGenArgTopic.NUM_IMAGES: NumImagesTaxonomy.FAL,
+ ImgGenArgTopic.OUTPUT_FORMAT: OutputFormatTaxonomy.SDXL,
+ }
+
+
+class TestImgGenParamSupport:
+ @pytest.mark.parametrize(
+ ("aspect_ratio", "expected_supported"),
+ [
+ (AspectRatio.SQUARE, True),
+ (AspectRatio.LANDSCAPE_3_2, True),
+ (AspectRatio.PORTRAIT_2_3, True),
+ (AspectRatio.LANDSCAPE_4_3, False),
+ (AspectRatio.PORTRAIT_9_16, False),
+ (AspectRatio.LANDSCAPE_21_9, False),
+ ],
+ )
+ def test_check_aspect_ratio_legacy_openai(self, aspect_ratio: AspectRatio, expected_supported: bool) -> None:
+ check = ImgGenParamSupport.check_aspect_ratio(
+ rules=_make_legacy_openai_rules(),
+ aspect_ratio=aspect_ratio,
+ size=None,
+ model_name="gpt-image-1",
+ )
+ assert check.is_supported is expected_supported
+ if not expected_supported:
+ assert check.reason is not None
+ assert "gpt-image-1" in check.reason
+
+ @pytest.mark.parametrize(
+ "aspect_ratio",
+ [
+ AspectRatio.SQUARE,
+ AspectRatio.LANDSCAPE_4_3,
+ AspectRatio.LANDSCAPE_16_9,
+ AspectRatio.PORTRAIT_9_16,
+ AspectRatio.LANDSCAPE_21_9,
+ ],
+ )
+ def test_check_aspect_ratio_gpt_image_2_supports_all_listed(self, aspect_ratio: AspectRatio) -> None:
+ check = ImgGenParamSupport.check_aspect_ratio(
+ rules=_make_gpt_image_2_rules(),
+ aspect_ratio=aspect_ratio,
+ size=None,
+ model_name="gpt-image-2",
+ )
+ assert check == SupportCheck(is_supported=True, reason=None)
+
+ @pytest.mark.parametrize(
+ ("background", "expected_supported"),
+ [
+ (Background.OPAQUE, True),
+ (Background.AUTO, True),
+ (Background.TRANSPARENT, False),
+ ],
+ )
+ def test_check_background_unavailable_rejects_transparent(self, background: Background, expected_supported: bool) -> None:
+ check = ImgGenParamSupport.check_background(
+ rules=_make_gpt_image_2_rules(),
+ background=background,
+ model_name="gpt-image-2",
+ )
+ assert check.is_supported is expected_supported
+ if not expected_supported:
+ assert check.reason is not None
+ assert "gpt-image-2" in check.reason
+ assert "transparent" in check.reason.lower()
+
+ @pytest.mark.parametrize(
+ "background",
+ [Background.OPAQUE, Background.AUTO, Background.TRANSPARENT],
+ )
+ def test_check_background_available_supports_all(self, background: Background) -> None:
+ check = ImgGenParamSupport.check_background(
+ rules=_make_legacy_openai_rules(),
+ background=background,
+ model_name="gpt-image-1",
+ )
+ assert check.is_supported is True
+
+ def test_check_output_format_sdxl_rejects_webp(self) -> None:
+ check = ImgGenParamSupport.check_output_format(
+ rules=_make_sdxl_rules(),
+ output_format=ImageFormat.WEBP,
+ )
+ assert check.is_supported is False
+ assert check.reason is not None
+ assert "WebP" in check.reason
+
+ @pytest.mark.parametrize("output_format", [ImageFormat.PNG, ImageFormat.JPEG])
+ def test_check_output_format_sdxl_accepts_png_jpeg(self, output_format: ImageFormat) -> None:
+ check = ImgGenParamSupport.check_output_format(
+ rules=_make_sdxl_rules(),
+ output_format=output_format,
+ )
+ assert check.is_supported is True
+
+ def test_check_output_format_none_is_supported(self) -> None:
+ """None means provider default — always considered supported regardless of taxonomy."""
+ for rules in [_make_legacy_openai_rules(), _make_gpt_image_2_rules(), _make_sdxl_rules()]:
+ check = ImgGenParamSupport.check_output_format(rules=rules, output_format=None)
+ assert check == SupportCheck(is_supported=True, reason=None)
+
+ def test_check_input_fidelity_unavailable_rejects_set_value(self) -> None:
+ check = ImgGenParamSupport.check_input_fidelity(
+ rules=_make_gpt_image_2_rules(),
+ input_fidelity=InputFidelity.HIGH,
+ model_name="gpt-image-2",
+ )
+ assert check.is_supported is False
+ assert check.reason is not None
+ assert "gpt-image-2" in check.reason
+ assert "input_fidelity" in check.reason
+
+ def test_check_input_fidelity_unavailable_accepts_none(self) -> None:
+ check = ImgGenParamSupport.check_input_fidelity(
+ rules=_make_gpt_image_2_rules(),
+ input_fidelity=None,
+ model_name="gpt-image-2",
+ )
+ assert check.is_supported is True
+
+ def test_check_input_fidelity_topic_missing_rejects_set_value(self) -> None:
+ rules: ImgGenModelRules = {ImgGenArgTopic.PROMPT: PromptTaxonomy.POSITIVE_ONLY}
+ check = ImgGenParamSupport.check_input_fidelity(
+ rules=rules,
+ input_fidelity=InputFidelity.LOW,
+ model_name="some-model",
+ )
+ assert check.is_supported is False
+ assert check.reason is not None
+ assert "some-model" in check.reason
+
+ def test_check_input_images_topic_present_supports(self) -> None:
+ check = ImgGenParamSupport.check_input_images_topic(rules=_make_legacy_openai_rules(), has_input_images=True)
+ assert check.is_supported is True
+
+ def test_check_input_images_topic_missing_rejects_when_provided(self) -> None:
+ rules: ImgGenModelRules = {ImgGenArgTopic.PROMPT: PromptTaxonomy.POSITIVE_ONLY}
+ check = ImgGenParamSupport.check_input_images_topic(rules=rules, has_input_images=True)
+ assert check.is_supported is False
+ assert check.reason is not None
+ assert "input_images" in check.reason
+
+ def test_check_input_images_topic_missing_supports_when_none(self) -> None:
+ rules: ImgGenModelRules = {ImgGenArgTopic.PROMPT: PromptTaxonomy.POSITIVE_ONLY}
+ check = ImgGenParamSupport.check_input_images_topic(rules=rules, has_input_images=False)
+ assert check.is_supported is True
+
+ def test_check_job_params_aggregate_legacy_openai_unsupported_aspect_ratio(self) -> None:
+ params = ImgGenJobParams(
+ aspect_ratio=AspectRatio.LANDSCAPE_4_3,
+ background=Background.OPAQUE,
+ output_format=ImageFormat.PNG,
+ )
+ reasons = ImgGenParamSupport.check_job_params(
+ rules=_make_legacy_openai_rules(),
+ params=params,
+ model_name="gpt-image-1",
+ )
+ assert len(reasons) == 1
+ assert "LANDSCAPE_4_3" in reasons[0] or "landscape_4_3" in reasons[0]
+
+ def test_check_job_params_aggregate_gpt_image_2_supports(self) -> None:
+ params = ImgGenJobParams(
+ aspect_ratio=AspectRatio.LANDSCAPE_4_3,
+ background=Background.OPAQUE,
+ output_format=ImageFormat.PNG,
+ )
+ reasons = ImgGenParamSupport.check_job_params(
+ rules=_make_gpt_image_2_rules(),
+ params=params,
+ model_name="gpt-image-2",
+ )
+ assert reasons == []
+
+ def test_check_job_params_aggregate_multiple_unsupported(self) -> None:
+ """gpt-image-2 rejects both transparent background and explicit input_fidelity."""
+ params = ImgGenJobParams(
+ aspect_ratio=AspectRatio.SQUARE,
+ background=Background.TRANSPARENT,
+ input_fidelity=InputFidelity.HIGH,
+ output_format=ImageFormat.PNG,
+ )
+ reasons = ImgGenParamSupport.check_job_params(
+ rules=_make_gpt_image_2_rules(),
+ params=params,
+ model_name="gpt-image-2",
+ )
+ assert len(reasons) == 2
+
+ def test_check_blueprint_params_skips_none_fields(self) -> None:
+ """Blueprint defers to deck defaults when fields are None — those should NOT be flagged."""
+ reasons = ImgGenParamSupport.check_blueprint_params(
+ rules=_make_legacy_openai_rules(),
+ aspect_ratio=None,
+ background=None,
+ output_format=None,
+ model_name="gpt-image-1",
+ )
+ assert reasons == []
+
+ def test_check_blueprint_params_flags_unsupported_aspect_ratio(self) -> None:
+ reasons = ImgGenParamSupport.check_blueprint_params(
+ rules=_make_legacy_openai_rules(),
+ aspect_ratio=AspectRatio.LANDSCAPE_4_3,
+ background=None,
+ output_format=None,
+ model_name="gpt-image-1",
+ )
+ assert len(reasons) == 1
+ assert "gpt-image-1" in reasons[0]
+
+ def test_check_aspect_ratio_with_explicit_size(self) -> None:
+ """For legacy OpenAI, explicit size also goes through the same checker."""
+ check = ImgGenParamSupport.check_aspect_ratio(
+ rules=_make_legacy_openai_rules(),
+ aspect_ratio=AspectRatio.SQUARE,
+ size=ImageSize(width=999, height=999),
+ model_name="gpt-image-1",
+ )
+ assert check.is_supported is False
+ assert check.reason is not None
+ assert "999x999" in check.reason
+
+ def test_empty_rules_supports_everything(self) -> None:
+ """An empty rules dict (no topic configured) means no taxonomy check kicks in."""
+ check = ImgGenParamSupport.check_aspect_ratio(
+ rules={},
+ aspect_ratio=AspectRatio.LANDSCAPE_4_3,
+ size=None,
+ model_name="any-model",
+ )
+ assert check.is_supported is True