Skip to content

The agent that grows with you

fix(image_gen): fall back only when Krea provably created no job, and apply the Krea default on first-run setup too

Mariano Nicolini4710e757abbb
diff --git a/hermes_cli/nous_subscription.py b/hermes_cli/nous_subscription.py
index f1ad85b6ebf..bb03b09840b 100644
--- a/hermes_cli/nous_subscription.py
+++ b/hermes_cli/nous_subscription.py
@@ -478,6 +478,14 @@ def _has_managed_default_direct(key: str) -> bool:
return bool(key in ("tts", "stt") and resolve_openai_audio_api_key()) or _any_env(*_FEATURES[key].default_direct_env)
+def _krea_image_default(config: dict[str, object], account_info) -> Optional[str]:
+ """Krea 2 Medium Turbo for accounts entitled to Krea when no image model is stored; the free
+ pool is not entitled and keeps the FAL default."""
+ if _section(config, "image_gen").get("model") or not (account_info and account_info.tool_gateway_entitled_for("krea")):
+ return None
+ return MANAGED_IMAGE_DEFAULT_KREA_MODEL
+
+
def apply_nous_managed_defaults(config: dict[str, object], *, enabled_toolsets: Optional[Iterable[str]] = None, force_fresh: bool = False) -> set[str]:
features = get_nous_subscription_features(config, force_fresh=force_fresh)
account_info = features.account_info
@@ -504,11 +512,9 @@ def apply_nous_managed_defaults(config: dict[str, object], *, enabled_toolsets:
# Video gen is not funded by the free tool pool: only wire managed video for entitled (paid) users.
for key, category in (("image_gen", None), ("video_gen", "fal-video")):
if key in selected_toolsets and not fal_key_is_configured() and (category is None or account_info.tool_gateway_entitled_for(category)):
- # Paid accounts default to Krea; the free pool is not entitled to it and keeps the FAL default.
model = None
- if (key == "image_gen" and not features.features[key].explicit_configured
- and not _section(config, key).get("model") and account_info.tool_gateway_entitled_for("krea")):
- model = MANAGED_IMAGE_DEFAULT_KREA_MODEL
+ if key == "image_gen" and not features.features[key].explicit_configured:
+ model = _krea_image_default(config, account_info)
_select_nous(config, key, model=model)
changed.add(key)
return changed
@@ -570,13 +576,13 @@ def get_gateway_eligible_tools(config: Optional[dict[str, object]] = None, *, fo
return unconfigured, has_direct, explicit_configured, already_managed
-def apply_gateway_defaults(config: dict[str, object], tool_keys: list[str]) -> set[str]:
+def apply_gateway_defaults(config: dict[str, object], tool_keys: list[str], account_info=None) -> set[str]:
"""Store the managed selection for ``tool_keys``; returns the set of tools actually changed."""
for key in _DEFAULT_SECTIONS:
_ensure_section(config, key)
changed = [key for key in _ALL_GATEWAY_KEYS if key in tool_keys] # table order: config key order
for key in changed:
- _select_nous(config, key)
+ _select_nous(config, key, model=_krea_image_default(config, account_info) if key == "image_gen" else None)
return set(changed)
@@ -624,7 +630,7 @@ def prompt_enable_tool_gateway(config: dict[str, object], *, force_fresh: bool =
newly_declined = [k for k in unconfigured if k not in chosen_keys and k not in declined]
if newly_declined or (declined & set(chosen_keys)):
config["tool_gateway_declined_tools"] = sorted((declined | set(newly_declined)) - set(chosen_keys))
- changed = apply_gateway_defaults(config, chosen_keys) if chosen_keys else set()
+ changed = apply_gateway_defaults(config, chosen_keys, account_info) if chosen_keys else set()
if changed or newly_declined:
from hermes_cli.config import save_config
diff --git a/plugins/image_gen/_common.py b/plugins/image_gen/_common.py
index 8412503d8e8..81b8b3cf743 100644
--- a/plugins/image_gen/_common.py
+++ b/plugins/image_gen/_common.py
@@ -240,7 +240,8 @@ def requests_error_message(response: Any, exc: Exception) -> str:
@dataclass
class HttpFailure:
"""One failed ``post_json`` attempt as ``(error, error_type)``. ``kind`` ∈ http / timeout /
- connection / request / invalid_json; ``message`` = HTTP error text or decode error;
+ unreachable (DNS failure or refused connection: nothing was sent) / connection (dropped
+ after connecting) / request / invalid_json; ``message`` = HTTP error text or decode error;
``status`` / ``response`` are set for ``http`` only."""
kind: str
@@ -270,6 +271,15 @@ def record_token_usage(usage: Any, *, model: str, provider: str, base_url: Optio
SimpleNamespace(model=model, usage=usage), "image_generation", provider=provider, base_url=base_url)
+def _never_connected(exc: Exception) -> bool:
+ """True when no connection was ever established, so the request body never left this host."""
+ from urllib3.exceptions import MaxRetryError, NameResolutionError, NewConnectionError
+
+ cause = exc.args[0] if exc.args else None
+ reason = cause.reason if isinstance(cause, MaxRetryError) else cause
+ return isinstance(reason, (NewConnectionError, NameResolutionError))
+
+
def post_json(
url: str, *, headers: dict[str, str], payload: dict[str, Any], timeout: Any, label: str,
error_message: Callable[[Any, Exception], str] = requests_error_message,
@@ -295,7 +305,8 @@ def post_json(
return None, HttpFailure(
"timeout", f"{label} image generation timed out ({int(read_timeout)}s)", "timeout")
except requests.ConnectionError as exc:
- return None, HttpFailure("connection", f"{label} connection error: {exc}", "connection_error")
+ kind = "unreachable" if _never_connected(exc) else "connection"
+ return None, HttpFailure(kind, f"{label} connection error: {exc}", "connection_error")
except requests.RequestException as exc:
if not catch_request_exception:
raise
diff --git a/plugins/image_gen/krea/__init__.py b/plugins/image_gen/krea/__init__.py
index 04d1c710271..3ea81085945 100644
--- a/plugins/image_gen/krea/__init__.py
+++ b/plugins/image_gen/krea/__init__.py
@@ -67,8 +67,6 @@ _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
@@ -113,9 +111,10 @@ def fallback_to_fal_enabled() -> bool:
def _fallback_eligible(failure: HttpFailure) -> bool:
- if failure.kind in ("connection", "request"):
- return True
- return failure.kind == "http" and failure.status in _FALLBACK_STATUSES
+ """Only failures that prove Krea created no job: the request never left this host, or the
+ gateway answered 429, which it documents as "no job was created". A dropped connection,
+ a timeout or a 5xx may have happened after Krea accepted the job."""
+ return failure.kind == "unreachable" or (failure.kind == "http" and failure.status == 429)
def _resolve_model(explicit: Optional[str] = None) -> tuple[str, dict[str, Any]]:
diff --git a/tests/hermes_cli/test_nous_subscription.py b/tests/hermes_cli/test_nous_subscription.py
index 4d4ba610e6c..2b24bff2f43 100644
--- a/tests/hermes_cli/test_nous_subscription.py
+++ b/tests/hermes_cli/test_nous_subscription.py
@@ -444,6 +444,21 @@ def test_pool_account_keeps_the_fal_image_default(monkeypatch):
assert "model" not in section
+def test_first_run_gateway_acceptance_writes_the_krea_image_model():
+ """`hermes setup --portal` stores selections through apply_gateway_defaults, not the managed-defaults
+ pass, so the Krea default must apply there too; an existing model and the free pool are left on FAL."""
+ paid, pool = _account(logged_in=True, paid=True), _pool_account()
+ fresh = {}
+ ns.apply_gateway_defaults(fresh, ["image_gen"], paid)
+ assert fresh["image_gen"] == {"provider": "nous", "model": ns.MANAGED_IMAGE_DEFAULT_KREA_MODEL}
+ pooled = {}
+ ns.apply_gateway_defaults(pooled, ["image_gen"], pool)
+ assert "model" not in pooled["image_gen"]
+ kept = {"image_gen": {"model": FAL_DEFAULT_MODEL}}
+ ns.apply_gateway_defaults(kept, ["image_gen"], paid)
+ assert kept["image_gen"]["model"] == FAL_DEFAULT_MODEL
+
+
def test_configured_image_section_is_left_alone(monkeypatch):
config = {"model": {"provider": "nous"}, "image_gen": {"provider": "nous", "model": FAL_DEFAULT_MODEL}}
section = _defaults_for(monkeypatch, _account(logged_in=True, paid=True), config)
diff --git a/tests/plugins/image_gen/test_krea_provider.py b/tests/plugins/image_gen/test_krea_provider.py
index d83c03b09ba..97b0f18f1ce 100644
--- a/tests/plugins/image_gen/test_krea_provider.py
+++ b/tests/plugins/image_gen/test_krea_provider.py
@@ -374,15 +374,23 @@ class TestGenerateErrors:
@pytest.mark.parametrize("failure, eligible", [
- ("connection", True), (503, True), (429, True), (422, False), ("timeout", False), ("invalid_json", False),
+ ("refused", True), (429, True), ("disconnected", False), (503, False), (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."""
+ """Only failures that prove Krea created no job may fall back: a connection that was never
+ established, or the gateway's 429. A connection dropped after sending, a timeout or a 5xx may
+ have happened after Krea accepted the job."""
import requests as req_lib
+ from urllib3.exceptions import MaxRetryError, NewConnectionError
from plugins.image_gen.krea import KreaImageGenProvider
- if failure == "connection":
- post = patch("plugins.image_gen.krea.requests.post", side_effect=req_lib.ConnectionError("refused"))
+ if failure == "refused":
+ refused = MaxRetryError(None, "http://x", reason=NewConnectionError(None, "Connection refused"))
+ post = patch("plugins.image_gen.krea.requests.post", side_effect=req_lib.ConnectionError(refused))
+ elif failure == "disconnected":
+ post = patch("plugins.image_gen.krea.requests.post",
+ side_effect=req_lib.ConnectionError("Remote end closed connection without response"))
elif failure == "timeout":
post = patch("plugins.image_gen.krea.requests.post", side_effect=req_lib.Timeout())
else:
diff --git a/tools/image_generation_tool.py b/tools/image_generation_tool.py
index 3bad979e965..5af23ba2118 100644
--- a/tools/image_generation_tool.py
+++ b/tools/image_generation_tool.py
@@ -797,8 +797,8 @@ def _handle_image_generate(args, **kw):
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.
+ Only the Krea plugin marks a failure ``fallback_eligible``, and only when the submit provably never
+ created a job: 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)
diff --git a/website/docs/user-guide/features/tool-gateway.md b/website/docs/user-guide/features/tool-gateway.md
index 7a2d794afd6..672b74656d8 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. 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.
+**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 (unreachable, or 429 after its own retries), 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.