Skip to content

The agent that grows with you

feat(image_gen): OpenAI image provider sends custom model ids verbatim and can reuse a named custom endpoint

teknium1fc08fdb1719b
diff --git a/plugins/image_gen/_common.py b/plugins/image_gen/_common.py
index aea9d21cda4..179cbec6a30 100644
--- a/plugins/image_gen/_common.py
+++ b/plugins/image_gen/_common.py
@@ -71,10 +71,15 @@ def load_image_gen_config(sub: Optional[str] = None) -> Dict[str, Any]:
def resolve_static_model(
models: Dict[str, Dict[str, Any]], default: str, *, env_var: str, config_key: str,
explicit: Optional[str] = None, include_top_level: bool = True,
- config: Optional[Dict[str, Any]] = None,
+ config: Optional[Dict[str, Any]] = None, passthrough: bool = False,
) -> Tuple[str, Dict[str, Any]]:
"""``(model_id, meta)`` from a fixed catalog; first *known* id wins (unknown ids fall through):
- explicit → ``env_var`` → ``image_gen.<config_key>.model`` → ``image_gen.model`` → ``default``."""
+ explicit → ``env_var`` → ``image_gen.<config_key>.model`` → ``image_gen.model`` → ``default``.
+
+ ``passthrough``: an unknown id from ``env_var`` or the provider-scoped ``image_gen.<config_key>.model``
+ is sent verbatim as the API model with no ``quality`` (OpenAI-compatible gateways serve their own
+ image model names and reject unknown enum values, #97928). The shared top-level ``image_gen.model``
+ never passes through — it may hold another provider's id."""
if isinstance(explicit, str) and explicit.strip() in models:
return explicit.strip(), models[explicit.strip()]
env_override = os.environ.get(env_var)
@@ -88,6 +93,10 @@ def resolve_static_model(
for candidate in candidates:
if isinstance(candidate, str) and candidate in models:
return candidate, models[candidate]
+ if passthrough:
+ custom = next((c.strip() for c in (env_override, candidates[0]) if isinstance(c, str) and c.strip()), "")
+ if custom:
+ return custom, {"display": custom, "api_model": custom, "quality": None}
return default, models[default]
diff --git a/plugins/image_gen/openai/__init__.py b/plugins/image_gen/openai/__init__.py
index d8da22ec76c..ca237b30084 100644
--- a/plugins/image_gen/openai/__init__.py
+++ b/plugins/image_gen/openai/__init__.py
@@ -1,7 +1,9 @@
"""OpenAI GPT Image 2 and 2.5 Flare/Sunburst quality tiers;
base64 output → image cache. Selection: ``OPENAI_IMAGE_MODEL`` → ``image_gen.openai.model`` →
-``image_gen.model`` → :data:`DEFAULT_MODEL`. Endpoint: ``image_gen.openai.base_url`` →
-``OPENAI_BASE_URL`` → SDK default; key: env named by ``image_gen.openai.key_env`` → ``OPENAI_API_KEY``."""
+``image_gen.model`` → :data:`DEFAULT_MODEL`; an id outside the catalog is sent verbatim.
+Endpoint: ``image_gen.openai.base_url`` → the named endpoint ``image_gen.openai.provider`` →
+``OPENAI_BASE_URL`` → SDK default; key: env named by ``image_gen.openai.key_env`` → the named
+endpoint's credential → ``OPENAI_API_KEY``."""
from __future__ import annotations
@@ -42,7 +44,22 @@ MODELS = {
def _resolve_model() -> Tuple[str, Dict[str, Any]]:
return resolve_static_model(
- MODELS, DEFAULT_MODEL, env_var="OPENAI_IMAGE_MODEL", config_key="openai")
+ MODELS, DEFAULT_MODEL, env_var="OPENAI_IMAGE_MODEL", config_key="openai", passthrough=True)
+
+
+def _named_endpoint(name: str) -> Tuple[str, str]:
+ """``(base_url, api_key)`` of the user-declared custom endpoint *name* (``providers:`` /
+ ``custom_providers:``), so image generation reuses a chat endpoint's URL and credential without
+ duplicating the key into OpenAI variables (#83080). Unknown name → ``("", "")`` with a warning."""
+ from hermes_cli.runtime_provider import _get_named_custom_provider
+
+ entry = _get_named_custom_provider(name)
+ if not entry:
+ logger.warning("image_gen.openai.provider %r matches no custom endpoint in providers:", name)
+ return "", ""
+ key_env = str(entry.get("key_env") or "").strip()
+ api_key = str(entry.get("api_key") or "").strip() or (get_secret(key_env) if key_env else None) or ""
+ return str(entry.get("base_url") or "").strip().rstrip("/"), api_key
def _resolve_endpoint() -> Tuple[str, str]:
@@ -50,9 +67,12 @@ def _resolve_endpoint() -> Tuple[str, str]:
the env var named by ``image_gen.openai.key_env`` → ``OPENAI_API_KEY``. Only the var NAME lives in
config.yaml; ``is_available()`` and ``generate()`` share this so they cannot disagree (#65309)."""
cfg = load_image_gen_config("openai")
- base_url = str(cfg.get("base_url") or "").strip().rstrip("/") or os.environ.get("OPENAI_BASE_URL", "").strip()
+ named = str(cfg.get("provider") or "").strip()
+ named_base, named_key = _named_endpoint(named) if named else ("", "")
+ base_url = (str(cfg.get("base_url") or "").strip().rstrip("/") or named_base
+ or os.environ.get("OPENAI_BASE_URL", "").strip())
key_env = str(cfg.get("key_env") or "").strip()
- api_key = (get_secret(key_env) if key_env else None) or get_secret("OPENAI_API_KEY") or ""
+ api_key = (get_secret(key_env) if key_env else None) or named_key or get_secret("OPENAI_API_KEY") or ""
return base_url, api_key
@@ -157,8 +177,10 @@ class OpenAIImageGenProvider(StaticImageGenProvider):
# gpt-image-2 returns b64_json unconditionally and REJECTS
# ``response_format`` as an unknown parameter. Don't send it.
- request: Dict[str, Any] = dict(
- model=meta["api_model"], prompt=prompt, size=size, n=1, quality=meta["quality"])
+ # A custom (non-catalog) model id carries no quality tier: gateways reject unknown enum values.
+ request: Dict[str, Any] = dict(model=meta["api_model"], prompt=prompt, size=size, n=1)
+ if meta["quality"] is not None:
+ request["quality"] = meta["quality"]
if is_edit:
try:
files = [_named_bytes_io(ref) for ref in sources]
diff --git a/tests/plugins/image_gen/test_openai_provider.py b/tests/plugins/image_gen/test_openai_provider.py
index 2daad0da4bf..4e2273e1bd8 100644
--- a/tests/plugins/image_gen/test_openai_provider.py
+++ b/tests/plugins/image_gen/test_openai_provider.py
@@ -130,6 +130,45 @@ class TestEndpointConfig:
assert kwargs["default_headers"]["OpenAI-Project"] == ""
kwargs["http_client"].close()
+ def test_custom_model_id_passes_through_without_quality(self, monkeypatch, tmp_path):
+ """A non-catalog ``image_gen.openai.model`` reaches the gateway verbatim as ``model`` and no
+ ``quality`` is sent (gateways reject unknown enum values); a stale top-level ``image_gen.model``
+ from another provider never passes through (#97928)."""
+ import yaml
+ monkeypatch.setenv("OPENAI_API_KEY", "k")
+ monkeypatch.delenv("OPENAI_IMAGE_MODEL", raising=False)
+ (tmp_path / "config.yaml").write_text(yaml.safe_dump({"image_gen": {
+ "model": "fal-ai/flux-2/klein/9b", "openai": {"model": "custom-image-model"}}}))
+ fake_client = MagicMock()
+ fake_client.images.generate.return_value = _fake_response(b64=_b64_png())
+ with _patched_openai(fake_client):
+ result = openai_plugin.OpenAIImageGenProvider().generate("a cat")
+ assert result["success"] is True and result["model"] == "custom-image-model"
+ request = fake_client.images.generate.call_args.kwargs
+ assert request["model"] == "custom-image-model" and "quality" not in request
+ (tmp_path / "config.yaml").write_text(yaml.safe_dump({"image_gen": {"model": "fal-ai/flux-2/klein/9b"}}))
+ assert openai_plugin._resolve_model()[0] == "gpt-image-2-medium"
+
+ def test_named_custom_endpoint_supplies_base_url_and_key(self, monkeypatch, tmp_path):
+ """``image_gen.openai.provider: <name>`` inherits that ``providers:`` entry's base_url and
+ key_env when ``base_url``/``key_env`` are unset; explicit values still win (#83080)."""
+ import yaml
+ for key in ("OPENAI_API_KEY", "OPENAI_BASE_URL"):
+ monkeypatch.delenv(key, raising=False)
+ monkeypatch.setenv("MY_GW_KEY", "gw-token")
+ monkeypatch.setenv("IMAGE_ONLY_KEY", "image-token")
+ (tmp_path / "config.yaml").write_text(yaml.safe_dump({
+ "providers": {"my-gateway": {"name": "My Gateway", "api": "https://gw.example/v1", "key_env": "MY_GW_KEY"}},
+ "image_gen": {"openai": {"provider": "my-gateway"}}}))
+ assert openai_plugin._resolve_endpoint() == ("https://gw.example/v1", "gw-token")
+ assert openai_plugin.OpenAIImageGenProvider().is_available() is True
+ (tmp_path / "config.yaml").write_text(yaml.safe_dump({
+ "providers": {"my-gateway": {"name": "My Gateway", "api": "https://gw.example/v1", "key_env": "MY_GW_KEY"}},
+ "image_gen": {"openai": {"provider": "my-gateway", "key_env": "IMAGE_ONLY_KEY"}}}))
+ assert openai_plugin._resolve_endpoint() == ("https://gw.example/v1", "image-token")
+ (tmp_path / "config.yaml").write_text(yaml.safe_dump({"image_gen": {"openai": {"provider": "no-such"}}}))
+ assert openai_plugin._resolve_endpoint() == ("", "")
+
def test_custom_base_url_ignores_system_proxy(self, monkeypatch):
"""httpx only sees macOS system proxies via ``urllib.request.getproxies()`` (ExceptionsList
dropped); the plugin's client must carry no proxy mount when no proxy env var is set."""
diff --git a/website/docs/user-guide/features/image-generation.md b/website/docs/user-guide/features/image-generation.md
index e5bc6b04901..2c9bd620b39 100644
--- a/website/docs/user-guide/features/image-generation.md
+++ b/website/docs/user-guide/features/image-generation.md
@@ -205,9 +205,7 @@ image_gen:
```
Only the variable *name* is stored in `config.yaml`; the secret stays in `.env`
-or the process environment. The model catalog is unchanged: `gpt-image-2-medium`
-is sent as `model: gpt-image-2` + `quality: medium`, so the gateway must serve
-OpenAI's image model names. Availability checks and
+or the process environment. Availability checks and
generation use the same resolution, so a configured `key_env` is enough — no
`OPENAI_API_KEY` is required. Requests go through Hermes' own HTTP client, which
honours `HTTP(S)_PROXY`/`NO_PROXY` but ignores macOS system proxies (whose
@@ -216,6 +214,39 @@ The `OpenAI-Project` header is sent blank on image requests: an `OPENAI_PROJECT_
set for chat otherwise makes the image endpoint return 403 `model_not_found` on
projects with a model allow-list, while the key itself already carries the project.
+**Gateway model names.** Catalog ids are mapped for OpenAI: `gpt-image-2-medium`
+is sent as `model: gpt-image-2` + `quality: medium`. Any other value of
+`image_gen.openai.model` (or `OPENAI_IMAGE_MODEL`) is sent verbatim as `model`
+with **no** `quality` field, so a gateway that serves its own image model names
+(`custom-image-model`, `grok-imagine-image`, ...) receives exactly that id and
+never sees a quality enum it might reject. The shared top-level `image_gen.model`
+is never passed through — it can hold another provider's id (a FAL path, for
+instance) from an earlier selection.
+
+**Reusing a named custom endpoint.** If the gateway is already declared under
+`providers:` for chat, point the image provider at it by *name* instead of
+repeating its URL and key:
+
+```yaml
+providers:
+ my-gateway:
+ name: My Gateway
+ api: https://gateway.example.com/v1
+ key_env: MY_GATEWAY_KEY
+
+image_gen:
+ provider: openai
+ openai:
+ provider: my-gateway # inherits api + key_env from providers.my-gateway
+ model: grok-imagine-image # sent verbatim, no quality
+```
+
+Resolution order is `image_gen.openai.base_url` → the named endpoint's URL →
+`OPENAI_BASE_URL`, and the variable named by `image_gen.openai.key_env` → the
+named endpoint's `api_key`/`key_env` → `OPENAI_API_KEY`; an explicit `base_url`
+or `key_env` next to `provider` therefore overrides that part of the endpoint. A
+name that matches no `providers:` entry is logged as a warning and ignored.
+
## Usage
The agent-facing schema is intentionally minimal — the model picks up whatever you've configured: