Skip to content

The agent that grows with you

feat(image_gen): fall back to FAL when managed Krea refuses a request before creating a job

Mariano Nicolinia9ebde190a8a
diff --git a/plugins/image_gen/krea/__init__.py b/plugins/image_gen/krea/__init__.py
index 45504d67304..04d1c710271 100644
--- a/plugins/image_gen/krea/__init__.py
+++ b/plugins/image_gen/krea/__init__.py
@@ -22,8 +22,8 @@ import requests
from agent.secret_scope import get_secret
from agent.image_gen_provider import DEFAULT_ASPECT_RATIO, resolve_aspect_ratio, save_url_image, success_response
from plugins.image_gen._common import (
- ErrorFn, StaticImageGenProvider, collect_source_images, error_factory, load_image_gen_config, post_json,
- prompt_required_error, resolve_static_model)
+ ErrorFn, HttpFailure, StaticImageGenProvider, collect_source_images, error_factory, load_image_gen_config,
+ post_json, prompt_required_error, resolve_static_model)
logger = logging.getLogger(__name__)
@@ -67,6 +67,8 @@ _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")
+# Submit failures that prove Krea never created a job, so a FAL retry cannot double-bill.
+_FALLBACK_STATUSES = frozenset({429, 500, 502, 503, 504})
# Polling: Krea recommends 2-5s; 2s backing off to 5s (Large ~1min); ceiling = Krea's 3 min tool timeout.
_POLL_INITIAL_INTERVAL = 2.0
@@ -105,6 +107,17 @@ def _krea_section() -> dict[str, Any]:
return section if isinstance(section, dict) else {}
+def fallback_to_fal_enabled() -> bool:
+ """``image_gen.krea.fallback_to_fal``; on unless set to false."""
+ return _krea_section().get("fallback_to_fal") is not False
+
+
+def _fallback_eligible(failure: HttpFailure) -> bool:
+ if failure.kind in ("connection", "request"):
+ return True
+ return failure.kind == "http" and failure.status in _FALLBACK_STATUSES
+
+
def _resolve_model(explicit: Optional[str] = None) -> tuple[str, dict[str, Any]]:
return resolve_static_model(
_MODELS, DEFAULT_MODEL, env_var="KREA_IMAGE_MODEL", config_key="krea", explicit=explicit,
@@ -388,6 +401,9 @@ def _submit_job(
headers=_headers(auth_token, managed=managed, json_body=True),
payload=payload, timeout=30, label="Krea", error_message=_submit_error_message)
if failure is not None:
+ def submit_fail(error: str, error_type: str) -> dict[str, Any]:
+ return {**fail(error, error_type), "fallback_eligible": _fallback_eligible(failure)}
+
if failure.kind == "http":
status, err_msg = failure.status, failure.message
logger.error("Krea submit failed (%d): %s", status, err_msg)
@@ -398,16 +414,16 @@ def _submit_job(
f"Model '{model_id}' may not be enabled/priced on the Nous Portal's Krea gateway. "
"Set KREA_API_KEY to use Krea directly, or pick a different model via "
"`hermes tools` → Image Generation.")
- return None, fail(
+ return None, submit_fail(
f"Nous Subscription Krea gateway rejected '{model_id}' "
f"(HTTP {status}): {err_msg}. {hint}",
"api_error")
- return None, fail(failure.error, "api_error")
+ return None, submit_fail(failure.error, "api_error")
if failure.kind == "timeout":
- return None, fail("Krea submit timed out (30s)", "timeout")
+ return None, submit_fail("Krea submit timed out (30s)", "timeout")
if failure.kind == "invalid_json":
- return None, fail(f"Krea returned invalid JSON on submit: {failure.message}", "invalid_response")
- return None, fail(failure.error, failure.error_type)
+ return None, submit_fail(f"Krea returned invalid JSON on submit: {failure.message}", "invalid_response")
+ return None, submit_fail(failure.error, failure.error_type)
job_id = submit_body.get("job_id")
if not isinstance(job_id, str) or not job_id:
return None, fail("Krea submit response missing job_id", "invalid_response")
diff --git a/tests/plugins/image_gen/test_krea_provider.py b/tests/plugins/image_gen/test_krea_provider.py
index 0ddd583b57a..d83c03b09ba 100644
--- a/tests/plugins/image_gen/test_krea_provider.py
+++ b/tests/plugins/image_gen/test_krea_provider.py
@@ -373,6 +373,31 @@ class TestGenerateErrors:
assert "Invalid API key" in result["error"]
+ @pytest.mark.parametrize("failure, eligible", [
+ ("connection", True), (503, True), (429, True), (422, False), ("timeout", False), ("invalid_json", False),
+ ])
+ def test_submit_failure_marks_whether_a_fal_fallback_is_safe(self, failure, eligible):
+ """Only failures that prove Krea created no job may fall back: connection errors, 429 and 5xx."""
+ import requests as req_lib
+ from plugins.image_gen.krea import KreaImageGenProvider
+
+ if failure == "connection":
+ post = patch("plugins.image_gen.krea.requests.post", side_effect=req_lib.ConnectionError("refused"))
+ elif failure == "timeout":
+ post = patch("plugins.image_gen.krea.requests.post", side_effect=req_lib.Timeout())
+ else:
+ resp = req_lib.Response()
+ resp.status_code = 200 if failure == "invalid_json" else failure
+ resp._content = b"not json" if failure == "invalid_json" else b'{"error": "nope"}'
+ resp.raise_for_status = MagicMock(side_effect=None if failure == "invalid_json" else req_lib.HTTPError(response=resp))
+ post = patch("plugins.image_gen.krea.requests.post", return_value=resp)
+
+ with post:
+ result = KreaImageGenProvider().generate(prompt="test")
+
+ assert result["success"] is False
+ assert result["fallback_eligible"] is eligible
+
def test_job_failed(self):
from plugins.image_gen.krea import KreaImageGenProvider
@@ -395,6 +420,7 @@ class TestGenerateErrors:
assert result["success"] is False
assert result["error_type"] == "api_error"
assert "NSFW" in result["error"]
+ assert "fallback_eligible" not in result
def test_completed_but_missing_urls(self):
diff --git a/tests/tools/test_image_generation_plugin_dispatch.py b/tests/tools/test_image_generation_plugin_dispatch.py
index 5e30948eb77..6439852f728 100644
--- a/tests/tools/test_image_generation_plugin_dispatch.py
+++ b/tests/tools/test_image_generation_plugin_dispatch.py
@@ -54,6 +54,51 @@ class TestPluginDispatch:
assert seen["intensity"] == 80
assert "creativity" not in seen
+ @pytest.mark.parametrize("eligible, image_url, enabled, fal_ok, falls_back", [
+ (True, None, True, True, True),
+ (False, None, True, True, False),
+ (True, "https://x/ref.png", True, True, False),
+ (True, None, False, True, False),
+ (True, None, True, False, True),
+ ])
+ def test_managed_krea_failure_falls_back_to_fal_only_when_safe(
+ self, monkeypatch, tmp_path, eligible, image_url, enabled, fal_ok, falls_back):
+ """Fallback runs for an eligible Krea failure with no source images and the switch on, and
+ names what ran; otherwise the Krea error is returned untouched."""
+ from tools import image_generation_tool as ig
+
+ krea_error = {"success": False, "image": None, "error": "Krea connection error", "error_type": "connection_error",
+ "fallback_eligible": eligible}
+ fal_calls = []
+
+ def fake_fal(prompt, aspect_ratio, **kwargs):
+ fal_calls.append(kwargs)
+ if fal_ok:
+ return json.dumps({"success": True, "image": "/tmp/fal.png", "modality": "text", "upscaled": False})
+ return json.dumps({"success": False, "image": None, "error": "FAL down", "error_type": "api_error"})
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr(ig, "_dispatch_to_plugin_provider", lambda *a, **k: None)
+ monkeypatch.setattr(ig, "_maybe_route_managed_model", lambda *a, **k: json.dumps(krea_error))
+ monkeypatch.setattr(ig, "image_generate_tool", fake_fal)
+ monkeypatch.setattr("plugins.image_gen.krea.fallback_to_fal_enabled", lambda: enabled)
+
+ args = {"prompt": "draw cat", "aspect_ratio": "square"}
+ if image_url:
+ args["image_url"] = image_url
+ result = json.loads(ig._handle_image_generate(args))
+
+ if not falls_back:
+ assert fal_calls == []
+ assert result["error"] == "Krea connection error"
+ assert "fallback_from" not in result
+ return
+ assert len(fal_calls) == 1 and fal_calls[0]["fal_model"] == ig.DEFAULT_MODEL
+ assert result["fallback_from"] == "krea"
+ assert result["fallback_reason"] == "Krea connection error"
+ assert "FAL" in result["note"]
+ assert result["success"] is fal_ok
+
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 d5271a70787..3bad979e965 100644
--- a/tools/image_generation_tool.py
+++ b/tools/image_generation_tool.py
@@ -419,14 +419,18 @@ def image_generate_tool(
num_inference_steps: Optional[int] = None, guidance_scale: Optional[float] = None,
num_images: Optional[int] = None, output_format: Optional[str] = None,
seed: Optional[int] = None, image_url: Optional[str] = None,
- reference_image_urls: Optional[list] = None, upscale: Optional[bool] = None) -> str:
+ reference_image_urls: Optional[list] = None, upscale: Optional[bool] = None,
+ fal_model: Optional[str] = None) -> str:
"""Generate (or, with source images + an ``edit_endpoint`` model, edit) an image via FAL.
Extra kwargs are overrides filtered per-model via ``supports`` / ``edit_supports`` (dropped
silently so callers survive model switches). Returns JSON ``{"success", "image", "modality",
"error", "error_type"}``.
"""
- model_id, meta = _resolve_fal_model()
+ if fal_model in FAL_MODELS:
+ model_id, meta = fal_model, FAL_MODELS[fal_model]
+ else:
+ model_id, meta = _resolve_fal_model()
refs = reference_image_urls if isinstance(reference_image_urls, (list, tuple)) else []
source_images = [c.strip() for c in (image_url, *refs) if isinstance(c, str) and c.strip()]
use_edit = bool(source_images) and bool(meta.get("edit_endpoint"))
@@ -780,16 +784,41 @@ def _handle_image_generate(args, **kw):
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):
- raw = route(prompt, aspect_ratio, controls=controls or None, **sources)
+ raw = _dispatch_to_plugin_provider(prompt, aspect_ratio, controls=controls or None, **sources)
+ if raw is None:
+ raw = _maybe_route_managed_model(prompt, aspect_ratio, controls=controls or None, **sources)
if raw is not None:
- break
+ raw = _fall_back_to_fal(raw, prompt, aspect_ratio, sources)
if raw is None:
raw = image_generate_tool(prompt, aspect_ratio, **sources)
return _postprocess_image_generate_result(raw, task_id=task_id)
+def _fall_back_to_fal(raw: str, prompt: str, aspect_ratio: str, sources: dict[str, Any]) -> str:
+ """Rerun a managed Krea request on FAL's default model when Krea refused it before creating a job.
+
+ Only the Krea plugin marks a failure ``fallback_eligible``, and only for connection errors, 429 and
+ 5xx on submit: a job that exists has already been authorized for billing and may still complete.
+ Source images never fall back; FAL would route them to an edit endpoint with different semantics."""
+ try:
+ result = json.loads(raw)
+ except Exception: # noqa: BLE001
+ return raw
+ if not isinstance(result, dict) or result.get("success") or not result.get("fallback_eligible"):
+ return raw
+ if sources.get("image_url") or sources.get("reference_image_urls"):
+ return raw
+ from plugins.image_gen.krea import fallback_to_fal_enabled
+ if not fallback_to_fal_enabled():
+ return raw
+ logger.warning("Managed Krea refused the request before starting a job; falling back to FAL: %s", result.get("error"))
+ fal_result = json.loads(image_generate_tool(prompt, aspect_ratio, upscale=sources.get("upscale"), fal_model=DEFAULT_MODEL))
+ fal_result.update(
+ provider="fal", model=DEFAULT_MODEL, fallback_from="krea", fallback_reason=result.get("error"),
+ note=f"Krea was unavailable, so this image was generated on FAL ({DEFAULT_MODEL}) instead.")
+ return json.dumps(fal_result)
+
+
# --- Dynamic schema — reflect the active backend's image-to-image capability ---
# Advertising edit capability up front saves a wasted turn. Memoized by config.yaml mtime in
# model_tools.get_tool_definitions(), so it rebuilds on switch.
diff --git a/website/docs/user-guide/features/tool-gateway.md b/website/docs/user-guide/features/tool-gateway.md
index 9fff184c107..7a2d794afd6 100644
--- a/website/docs/user-guide/features/tool-gateway.md
+++ b/website/docs/user-guide/features/tool-gateway.md
@@ -115,7 +115,7 @@ The model is chosen once, in `hermes tools` → Image Generation, and stored in
The **Nous Subscription** row has one model picker that lists every model once. The stored id decides which gateway serves the request: a native Krea id (`krea-2-medium`, `krea-2-large`, `krea-2-medium-turbo`) goes to the Krea gateway, a FAL catalog id goes to FAL, and any other id goes to Nous Portal. The selection is still just `image_gen.provider: nous` plus the model id.
-**Krea 2** (Medium, Large, Medium Turbo — up to 10 style-reference images, optional Enhance upscale) and the Nous Portal image models sit in that same picker rather than behind rows of their own. They need a paid subscription — the free tool pool funds the FAL models only. The Krea-via-FAL ids (`fal-ai/krea/v2/...`) stay on the direct FAL.ai row.
+**Krea 2** (Medium, Large, Medium Turbo — up to 10 style-reference images, optional Enhance upscale) and the Nous Portal image models sit in that same picker rather than behind rows of their own. They need a paid subscription — the free tool pool funds the FAL models only. The Krea-via-FAL ids (`fal-ai/krea/v2/...`) stay on the direct FAL.ai row. If the Krea gateway refuses a request before starting a job (connection error, 429 after retries, or a 5xx), Hermes reruns it on the FAL default model and the result says so in `fallback_from`; set `image_gen.krea.fallback_to_fal: false` to turn that off. Requests with source images never fall back.
Model ids, speeds, and prices live on the [Image Generation](./image-generation.md#supported-models) page. The set evolves — `hermes tools` → Image Generation shows the current live list.