Skip to content

The agent that grows with you

feat(image_gen): expose the Krea 2 sliders to the agent only when the active backend declares them

Mariano Nicolinibf1bc78e638d
diff --git a/plugins/image_gen/krea/__init__.py b/plugins/image_gen/krea/__init__.py
index 1b96f5a7813..3049e026a73 100644
--- a/plugins/image_gen/krea/__init__.py
+++ b/plugins/image_gen/krea/__init__.py
@@ -66,6 +66,8 @@ _REMOTE_REFERENCE_PREFIXES = ("http://", "https://", "data:")
# so all local references together stay under this.
_MAX_LOCAL_REFERENCE_BYTES = 3 * 1024 * 1024
_VALID_CREATIVITY = {"raw", "low", "medium", "high"}
+# Krea 2 generative sliders: integers from -100 to 100, 0 means the slider is off.
+_K2_SLIDERS = ("intensity", "complexity", "movement")
# Polling: Krea recommends 2-5s; 2s backing off to 5s (Large ~1min); ceiling = Krea's 3 min tool timeout.
_POLL_INITIAL_INTERVAL = 2.0
@@ -350,6 +352,10 @@ def _build_payload(
}
if isinstance(kwargs.get("seed"), int):
payload["seed"] = kwargs["seed"]
+ for slider in _K2_SLIDERS:
+ value = kwargs.get(slider)
+ if isinstance(value, int) and not isinstance(value, bool) and -100 <= value <= 100:
+ payload[slider] = value
styles, moodboards = kwargs.get("styles"), kwargs.get("moodboards")
if isinstance(styles, list) and styles:
payload["styles"] = styles
@@ -445,7 +451,7 @@ class KreaImageGenProvider(StaticImageGenProvider):
def capabilities(self) -> Dict[str, Any]:
return {
"modalities": ["text", "image"], "max_reference_images": _MAX_STYLE_REFERENCES,
- "supports_upscale": True,
+ "supports_upscale": True, "creative_controls": ["creativity", *_K2_SLIDERS],
}
def generate(
diff --git a/tests/plugins/image_gen/test_krea_provider.py b/tests/plugins/image_gen/test_krea_provider.py
index fe6095b38c6..a29b18c8ba6 100644
--- a/tests/plugins/image_gen/test_krea_provider.py
+++ b/tests/plugins/image_gen/test_krea_provider.py
@@ -233,6 +233,24 @@ class TestGenerate:
assert len(payload["image_style_references"]) == 10 # capped at 10
assert payload["creativity"] == "high"
+ def test_sliders_reach_payload_and_out_of_range_values_are_dropped(self):
+ from plugins.image_gen.krea import KreaImageGenProvider
+
+ submit = _submit_response()
+ poll = _poll_response(_completed_job())
+
+ with patch("plugins.image_gen.krea.requests.post", return_value=submit) as mock_post, \
+ patch("plugins.image_gen.krea.requests.get", return_value=poll), \
+ patch("plugins.image_gen.krea.save_url_image", return_value=Path("/tmp/x.png")), \
+ patch("plugins.image_gen.krea.time.sleep"):
+ KreaImageGenProvider().generate(
+ prompt="test", intensity=80, complexity=-100, movement=150, upscale=False)
+
+ payload = mock_post.call_args.kwargs["json"]
+ assert payload["intensity"] == 80
+ assert payload["complexity"] == -100
+ assert "movement" not in payload
+
def test_string_style_references_converted_to_objects(self):
"""Krea requires {url, strength} objects; bare URL strings must be
converted (a string yields a 422 'Expected object, received string')."""
diff --git a/tests/tools/test_image_generate_schema.py b/tests/tools/test_image_generate_schema.py
index c656ebb6d73..7397f9eef74 100644
--- a/tests/tools/test_image_generate_schema.py
+++ b/tests/tools/test_image_generate_schema.py
@@ -118,6 +118,23 @@ class TestDynamicParamGating(unittest.TestCase):
)
self.assertIn("upscale", props)
+ def test_managed_krea_model_advertises_creative_controls(self):
+ with patch.object(ig, "_read_configured_image_provider",
+ return_value="nous"), \
+ patch.object(ig, "_read_configured_image_model",
+ return_value="krea-2-medium"):
+ props = _build_dynamic_image_schema()["parameters"]["properties"]
+ self.assertEqual(props["creativity"]["enum"], ["raw", "low", "medium", "high"])
+ for name in ("intensity", "complexity", "movement"):
+ self.assertEqual(props[name]["type"], "integer", name)
+ self.assertEqual((props[name]["minimum"], props[name]["maximum"]), (-100, 100), name)
+
+ def test_fal_models_hide_creative_controls(self):
+ for model in (self._t2i_only(), self._edit_multi_ref()):
+ props = self._schema_for(model)["parameters"]["properties"]
+ for name in ("creativity", "intensity", "complexity", "movement"):
+ self.assertNotIn(name, props, model)
+
def test_static_schema_carries_no_capability_args(self):
"""The registration-time placeholder must stay minimal — dynamic
overrides own the capability args (do-not-re-add guard)."""
diff --git a/tests/tools/test_image_generation_plugin_dispatch.py b/tests/tools/test_image_generation_plugin_dispatch.py
index 0086653770a..1fb2b010eda 100644
--- a/tests/tools/test_image_generation_plugin_dispatch.py
+++ b/tests/tools/test_image_generation_plugin_dispatch.py
@@ -15,6 +15,31 @@ def _reset_registry():
class TestPluginDispatch:
+ def test_handler_forwards_creative_controls_to_the_plugin(self, monkeypatch, tmp_path):
+ from tools import image_generation_tool
+ from agent import image_gen_registry as registry_module
+ from hermes_cli import plugins as plugins_module
+
+ seen = {}
+
+ class _Recorder(_FakeCodexProvider):
+ def generate(self, prompt, aspect_ratio="landscape", **kwargs):
+ seen.update(kwargs)
+ return super().generate(prompt, aspect_ratio, **kwargs)
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "config.yaml").write_text("image_gen:\n provider: codex\n")
+ monkeypatch.setattr(image_generation_tool, "_read_configured_image_provider", lambda: "codex")
+ monkeypatch.setattr(plugins_module, "_ensure_plugins_discovered", lambda: None)
+ monkeypatch.setattr(registry_module, "get_provider", lambda name: _Recorder() if name == "codex" else None)
+
+ result = json.loads(image_generation_tool._handle_image_generate(
+ {"prompt": "draw cat", "aspect_ratio": "square", "intensity": 80, "creativity": "raw"}))
+
+ assert result["success"] is True
+ assert seen["intensity"] == 80
+ assert seen["creativity"] == "raw"
+
def test_deepinfra_key_alone_does_not_select_image_backend(self, monkeypatch):
"""DeepInfra chat credentials do not imply consent to image billing."""
from tools import image_generation_tool
diff --git a/tools/image_generation_tool.py b/tools/image_generation_tool.py
index 2ad502aa530..4fff5f5fee1 100644
--- a/tools/image_generation_tool.py
+++ b/tools/image_generation_tool.py
@@ -598,10 +598,12 @@ def _provider_result(result, contract_error: str) -> str:
return json.dumps(result)
-def _add_provider_kwargs(kwargs, image_url, reference_image_urls, upscale, model=None) -> Dict[str, Any]:
+def _add_provider_kwargs(kwargs, image_url, reference_image_urls, upscale, model=None, controls=None) -> Dict[str, Any]:
"""Add the optional ``provider.generate(**kwargs)`` args in place (edit args only when supplied)."""
if model:
kwargs["model"] = model
+ if controls:
+ kwargs.update(controls)
if isinstance(image_url, str) and image_url.strip():
kwargs["image_url"] = image_url.strip()
if reference_image_urls is not None:
@@ -616,7 +618,8 @@ def _add_provider_kwargs(kwargs, image_url, reference_image_urls, upscale, model
def _dispatch_to_plugin_provider(
prompt: str, aspect_ratio: str, image_url: Optional[str] = None,
- reference_image_urls: Optional[list] = None, upscale: Optional[bool] = None):
+ reference_image_urls: Optional[list] = None, upscale: Optional[bool] = None,
+ controls: Optional[Dict[str, Any]] = None):
"""JSON result from the selected plugin provider, or ``None`` to fall through to in-tree FAL
(provider unset / ``"fal"`` / ``"nous"``). Providers without ``upscale`` ignore it via ``**kwargs``."""
configured = _plugin_provider_name()
@@ -642,7 +645,7 @@ def _dispatch_to_plugin_provider(
kwargs: Dict[str, Any] = {"prompt": prompt, "aspect_ratio": aspect_ratio}
try:
_add_provider_kwargs(kwargs, image_url, reference_image_urls, upscale,
- model=_read_configured_image_model())
+ model=_read_configured_image_model(), controls=controls)
result = provider.generate(**kwargs)
except Exception as exc:
# A TypeError from generate() predating image_url support (third-party plugin not yet
@@ -693,7 +696,8 @@ def _managed_model_plugin() -> Optional[tuple]:
def _maybe_route_managed_model(
prompt: str, aspect_ratio: str, image_url: Optional[str] = None,
- reference_image_urls: Optional[list] = None, upscale: Optional[bool] = None) -> Optional[str]:
+ reference_image_urls: Optional[list] = None, upscale: Optional[bool] = None,
+ controls: Optional[Dict[str, Any]] = None) -> Optional[str]:
"""JSON result from the Krea or Portal gateway the stored model belongs to, or ``None`` to fall
through to FAL.
@@ -721,7 +725,7 @@ def _maybe_route_managed_model(
f"available. Pick another model via `hermes tools` → Image Generation.", "provider_not_registered")
kwargs: Dict[str, Any] = {"prompt": prompt, "aspect_ratio": aspect_ratio, "model": model_id}
try:
- _add_provider_kwargs(kwargs, image_url, reference_image_urls, upscale)
+ _add_provider_kwargs(kwargs, image_url, reference_image_urls, upscale, controls=controls)
result = provider.generate(**kwargs)
except Exception as exc: # noqa: BLE001
logger.warning("Managed %s routing failed: %s", plugin_name, exc)
@@ -771,11 +775,14 @@ def _handle_image_generate(args, **kw):
# Portal — only under the "nous"/unset selection, so BYO/direct FAL stays untouched), then FAL.
sources = dict(image_url=image_url, reference_image_urls=reference_image_urls,
upscale=upscale if isinstance(upscale, bool) else None)
+ controls = {name: args[name] for name in _CREATIVE_CONTROL_PARAMS if name in args}
raw = None
- for route in (_dispatch_to_plugin_provider, _maybe_route_managed_model, image_generate_tool):
- raw = route(prompt, aspect_ratio, **sources)
+ for route in (_dispatch_to_plugin_provider, _maybe_route_managed_model):
+ raw = route(prompt, aspect_ratio, controls=controls or None, **sources)
if raw is not None:
break
+ if raw is None:
+ raw = image_generate_tool(prompt, aspect_ratio, **sources)
return _postprocess_image_generate_result(raw, task_id=task_id)
@@ -817,6 +824,8 @@ def _active_image_capabilities() -> Dict[str, Any]:
info["max_reference_images"] = int(caps["max_reference_images"])
# Plugins opt in explicitly; absent = no upscale param.
info["supports_upscale"] = bool(caps.get("supports_upscale"))
+ if caps.get("creative_controls"):
+ info["creative_controls"] = list(caps["creative_controls"])
return info
except Exception: # noqa: BLE001
pass
@@ -842,6 +851,26 @@ _IMAGE_URL_PARAM = {
),
}
+# Krea 2 exposes these; a provider advertises the ones it honors via ``creative_controls``.
+_CREATIVE_CONTROL_PARAMS = {
+ "creativity": {
+ "type": "string", "enum": ["raw", "low", "medium", "high"],
+ "description": "Prompt expansion: raw (none), low, medium or high.",
+ },
+ "intensity": {
+ "type": "integer", "minimum": -100, "maximum": 100,
+ "description": "Style intensity, -100 muted to 100 highly stylized. 0 neutral.",
+ },
+ "complexity": {
+ "type": "integer", "minimum": -100, "maximum": 100,
+ "description": "Composition density, -100 minimal to 100 dense. 0 neutral.",
+ },
+ "movement": {
+ "type": "integer", "minimum": -100, "maximum": 100,
+ "description": "Motion in the scene, -100 static to 100 dynamic. 0 neutral.",
+ },
+}
+
_UPSCALE_PARAM = {
"type": "boolean",
"description": (
@@ -886,6 +915,9 @@ def _build_dynamic_image_schema() -> Dict[str, Any]:
edit_clause = " (text-to-image only — the active model cannot edit existing images)"
if info.get("supports_upscale"):
properties["upscale"] = _UPSCALE_PARAM
+ for name in info.get("creative_controls") or []:
+ if name in _CREATIVE_CONTROL_PARAMS:
+ properties[name] = _CREATIVE_CONTROL_PARAMS[name]
return {"description": base_desc.format(edit_clause=edit_clause),
"parameters": {"type": "object", "properties": properties, "required": ["prompt"]}}
diff --git a/website/docs/user-guide/features/image-generation.md b/website/docs/user-guide/features/image-generation.md
index 2a33552c650..7c4f5738af0 100644
--- a/website/docs/user-guide/features/image-generation.md
+++ b/website/docs/user-guide/features/image-generation.md
@@ -32,7 +32,7 @@ Prices are FAL's pricing at time of writing; check [fal.ai](https://fal.ai/) for
:::tip Nous Subscribers
If you have a paid [Nous Portal](https://portal.nousresearch.com) subscription, you can use image generation through the **[Tool Gateway](tool-gateway.md)** without a FAL API key. Your model selection persists across both paths. New installs can run `hermes setup --portal` to log in and turn on every gateway tool at once; existing installs can pick **Nous Subscription** as the image-gen backend via `hermes tools`.
-The **Nous Subscription** row is the only managed row. Its model picker spans every gateway the subscription runs — the FAL catalog above, native **Krea 2** (`krea-2-medium`, `krea-2-large`, `krea-2-medium-turbo`) and any Nous Portal image models — each model listed once, and the model you pick decides which gateway serves the request. Free tool-pool accounts see the FAL models only; Krea and Portal models are paid-subscription.
+The **Nous Subscription** row is the only managed row. Its model picker spans every gateway the subscription runs — the FAL catalog above, native **Krea 2** (`krea-2-medium`, `krea-2-large`, `krea-2-medium-turbo`) and any Nous Portal image models — each model listed once, and the model you pick decides which gateway serves the request. Free tool-pool accounts see the FAL models only; Krea and Portal models are paid-subscription. With a Krea 2 model selected, `image_generate` also offers Krea's `creativity` setting and its `intensity`, `complexity` and `movement` sliders (-100 to 100).
If the managed gateway returns `HTTP 4xx` for a specific model, that model isn't yet proxied on the portal side — the agent will tell you so, with remediation steps (switch to FAL.ai in `hermes tools` with your own `FAL_KEY` for direct access, or pick a different model).
:::