The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(image_gen/openrouter): collapse nested-shape guards into _dict_at/_list_at, table enum/int knobs, compact data tables
Tekniume3aae5b6db8e
diff --git a/plugins/image_gen/openrouter/__init__.py b/plugins/image_gen/openrouter/__init__.pyindex db22b12f1d3..4c826715fcd 100644--- a/plugins/image_gen/openrouter/__init__.py+++ b/plugins/image_gen/openrouter/__init__.py@@ -23,9 +23,7 @@ from agent.image_gen_provider import (DEFAULT_ASPECT_RATIO, ImageGenProvider, error_response, resolve_aspect_ratio, save_b64_image,save_url_image, success_response,)-from plugins.image_gen._common import (- HttpFailure as HttpFailure, error_factory, load_image_gen_config, post_json-)+from plugins.image_gen._common import error_factory, load_image_gen_config, post_jsonlogger = logging.getLogger(__name__)@@ -65,23 +63,23 @@ _load_image_gen_config = load_image_gen_config# OpenRouter Dedicated Image API (POST /images/generations)# ----------------------------------------------------------------------------#: Env prefix for Image API knobs (``OPENROUTER_IMAGE_API_QUALITY`` …); distinct-#: from ``OPENROUTER_IMAGE_MODEL`` which selects the model on either surface.+# Env prefix for Image API knobs (``OPENROUTER_IMAGE_API_QUALITY`` …); distinct+# from ``OPENROUTER_IMAGE_MODEL`` which selects the model on either surface._IMAGE_API_ENV_PREFIX = "OPENROUTER_IMAGE_API_"-#: Connect budget separate from the read budget: no TLS in 20s means the-#: endpoint is down, and waiting out the generation timeout only delays the error.+# Connect budget separate from the read budget: no TLS in 20s means the endpoint+# is down, and waiting out the generation timeout only delays the error._IMAGE_API_CONNECT_TIMEOUT = 20.0-#: Cached ``/images/models`` probes keyed by base URL: ``(fetched_at, ids)``.-#: Empty sets are cached too, so a failing endpoint is probed once per TTL.+# ``/images/models`` probes keyed by base URL: ``(fetched_at, ids)``. Empty sets+# are cached too, so a failing endpoint is probed once per TTL._CATALOG_TTL_SECONDS = 900.0_CATALOG_CACHE: Dict[str, Tuple[float, frozenset]] = {}_GEMINI_RATIOS = (- "1:1", "1:4", "1:8", "2:3", "3:2", "3:4", "4:1", "4:3",- "4:5", "5:4", "8:1", "9:16", "16:9", "21:9",+ "1:1", "1:4", "1:8", "2:3", "3:2", "3:4", "4:1", "4:3", "4:5", "5:4", "8:1", "9:16", "16:9", "21:9",)_MAI_RATIOS = ("1:1", "4:3", "3:4", "16:9", "9:16", "3:2", "2:3", "auto")_KREA_RATIOS = ("1:1", "4:3", "3:2", "16:9", "4:5", "2:3", "9:16")+_OPENAI_QUALITY = ("auto", "low", "medium", "high")_NO_KNOBS = {"quality": (), "background": (), "output_format": (), "compression": False, "seed": False}@@ -90,10 +88,10 @@ def _image_api_model(display: str, strengths: str, **spec: Any) -> Dict[str, Anyreturn {"display": display, "strengths": strengths, **_NO_KNOBS, "resolutions": (), **spec}-#: Curated Image API models and the parameters each declares in ``GET-#: /images/models``. An id missing here still works — it just gets no per-model-#: parameter filtering and costs one cached catalog probe to recognise. Keys-#: mirror the payload field they gate; an empty tuple means "no such knob".+# Curated Image API models and the parameters each declares in ``GET /images/models``.+# An id missing here still works — it just gets no per-model parameter filtering+# and costs one cached catalog probe to recognise. Keys mirror the payload field+# they gate; an empty tuple means "no such knob"._IMAGE_API_MODELS: Dict[str, Dict[str, Any]] = {"google/gemini-3.1-flash-lite-image": _image_api_model("Nano Banana 2 Lite (Gemini 3.1 Flash Lite Image)",@@ -109,15 +107,14 @@ _IMAGE_API_MODELS: Dict[str, Dict[str, Any]] = {"OpenAI GPT Image 2","Best editing fidelity; up to 16 references; strongest prompt adherence",aspect_ratios=("1:1", "3:2", "2:3", "4:3", "3:4", "16:9", "9:16", "21:9", "auto"),- quality=("auto", "low", "medium", "high"), background=("auto", "opaque"),- compression=True, max_n=10, max_refs=16,+ quality=_OPENAI_QUALITY, background=("auto", "opaque"), compression=True, max_n=10, max_refs=16,),"openai/gpt-image-1-mini": _image_api_model("OpenAI GPT Image 1 Mini","The only model here with background=transparent (cut-out PNG)",aspect_ratios=("1:1", "3:2", "2:3", "auto"),- quality=("auto", "low", "medium", "high"), background=("auto", "transparent", "opaque"),- compression=True, max_n=10, max_refs=16,+ quality=_OPENAI_QUALITY, background=("auto", "transparent", "opaque"), compression=True,+ max_n=10, max_refs=16,),"microsoft/mai-image-2.5": _image_api_model("Microsoft MAI-Image-2.5", "Standard ratios; a good second opinion next to Gemini",@@ -131,8 +128,8 @@ _IMAGE_API_MODELS: Dict[str, Dict[str, Any]] = {"Grok Imagine (Image Quality)","Photoreal; widest exotic-ratio set (9:19.5, 20:9, 2:1 …); 1K/2K",aspect_ratios=(- "1:1", "3:4", "4:3", "9:16", "16:9", "2:3", "3:2",- "9:19.5", "19.5:9", "9:20", "20:9", "1:2", "2:1", "auto",+ "1:1", "3:4", "4:3", "9:16", "16:9", "2:3", "3:2", "9:19.5", "19.5:9", "9:20", "20:9", "1:2", "2:1",+ "auto",),resolutions=("1K", "2K"), max_n=1, max_refs=3,),@@ -146,28 +143,24 @@ _IMAGE_API_MODELS: Dict[str, Dict[str, Any]] = {),"qwen/qwen-image-3-pro": _image_api_model("Qwen Image 3 Pro", "Precise small text and detail rendering; n up to 6; 1K/2K; seed",- aspect_ratios=(- "1:1", "1:2", "1:4", "2:1", "2:3", "3:2", "3:4",- "4:1", "4:3", "4:5", "5:4", "9:16", "16:9",- ),+ aspect_ratios=("1:1", "1:2", "1:4", "2:1", "2:3", "3:2", "3:4", "4:1", "4:3", "4:5", "5:4", "9:16", "16:9"),resolutions=("1K", "2K"), seed=True, max_n=6, max_refs=4,),}-#: Applied to a catalog model the table doesn't describe. Empty ``aspect_ratios``-#: means "enum unknown" and the field is omitted rather than guessed.+# Applied to a catalog model the table doesn't describe. Empty ``aspect_ratios``+# means "enum unknown" and the field is omitted rather than guessed._UNKNOWN_IMAGE_API_MODEL = _image_api_model("", "", aspect_ratios=(), max_n=1, max_refs=16)-#: Union of exact ratios the endpoint accepts across all models; sanity-checks-#: an override aimed at a model whose own enum we don't know.+# Union of exact ratios the endpoint accepts across all models; sanity-checks an+# override aimed at a model whose own enum we don't know._ENDPOINT_ASPECT_RATIOS = frozenset({- "1:1", "1:2", "1:4", "1:8", "2:1", "2:3", "3:2", "3:4", "4:1", "4:3",- "4:5", "5:4", "8:1", "9:16", "16:9", "9:19.5", "19.5:9", "9:20", "20:9",- "9:21", "21:9", "auto",+ "1:1", "1:2", "1:4", "1:8", "2:1", "2:3", "3:2", "3:4", "4:1", "4:3", "4:5", "5:4", "8:1", "9:16",+ "16:9", "9:19.5", "19.5:9", "9:20", "20:9", "9:21", "21:9", "auto",})-#: Semantic ratio → exact ratios, best first (``landscape`` degrades to 3:2 on-#: ``gpt-image-1-mini``, which has no 16:9).+# Semantic ratio → exact ratios, best first (``landscape`` degrades to 3:2 on+# ``gpt-image-1-mini``, which has no 16:9)._ASPECT_PREFERENCES: Dict[str, Tuple[str, ...]] = {"landscape": ("16:9", "3:2", "4:3", "5:4", "21:9", "2:1", "19.5:9", "20:9", "4:1", "8:1"),"portrait": ("9:16", "2:3", "3:4", "4:5", "9:21", "1:2", "9:19.5", "9:20", "1:4", "1:8"),@@ -175,23 +168,39 @@ _ASPECT_PREFERENCES: Dict[str, Tuple[str, ...]] = {}_MEDIA_TYPE_EXTENSIONS = {- "image/png": "png", "image/jpeg": "jpg", "image/jpg": "jpg",- "image/webp": "webp", "image/gif": "gif", "image/svg+xml": "svg",+ "image/png": "png", "image/jpeg": "jpg", "image/jpg": "jpg", "image/webp": "webp", "image/gif": "gif",+ "image/svg+xml": "svg",}-#: HTTP statuses worth retrying on the next model of the chain. 400 is our own-#: payload and would repeat; 401/403 are account-level and answered before this-#: set is consulted. 502 is how the all-or-nothing-billed Image API reports a-#: failed (unbilled) generation.+# HTTP statuses worth retrying on the next model of the chain. 400 is our own+# payload and would repeat; 401/403 are account-level and answered before this+# set is consulted. 502 is how the all-or-nothing-billed Image API reports a+# failed (unbilled) generation._IMAGE_API_FALLBACK_STATUSES = frozenset({402, 404, 408, 409, 425, 429, 500, 502, 503, 504})-#: Ids that stay on ``/chat/completions`` whatever the image catalog says —-#: they are this backend's tested defaults.+# Ids that stay on ``/chat/completions`` whatever the image catalog says — they+# are this backend's tested defaults._CHAT_ONLY_MODELS = frozenset({DEFAULT_MODEL, _FALLBACK_MODEL})-#: Image API payload knobs copied into the success ``extra``.+# Image API payload knobs copied into the success ``extra``._IMAGE_API_EXTRA_KEYS = ("resolution", "quality", "background", "output_format", "seed", "n")+# Enum knobs: payload field → catalog key holding the allowed values.+_IMAGE_API_ENUMS = (+ ("resolution", "resolutions"), ("quality", None), ("background", None), ("output_format", None),+)+# Integer knobs: payload field → (catalog gate flag, clamp).+_IMAGE_API_INTS = (+ ("output_compression", "compression", lambda v: max(0, min(100, v))), ("seed", "seed", lambda v: v),+)++_ATTRIBUTION_HEADERS = {+ "Content-Type": "application/json",+ # OpenRouter attribution headers (harmless against Nous Portal).+ "HTTP-Referer": "https://github.com/NousResearch/hermes-agent",+ "X-Title": "Hermes Agent",+}+def _to_image_url_part(ref: str) -> Optional[str]:"""``image_url`` value for a reference: URLs pass through, local files are@@ -215,24 +224,28 @@ def _to_image_url_part(ref: str) -> Optional[str]:return f"data:{mime};base64,{base64.b64encode(raw).decode('ascii')}"+def _dict_at(node: Any, key: str) -> Dict[str, Any]:+ value = node.get(key) if isinstance(node, dict) else None+ return value if isinstance(value, dict) else {}+++def _list_at(node: Any, key: str) -> List[Any]:+ value = node.get(key) if isinstance(node, dict) else None+ return value if isinstance(value, list) else []++def _extract_images(payload: Dict[str, Any]) -> List[str]:"""Generated image URLs from ``choices[].message.images[].image_url.url``."""out: List[str] = []- choices = payload.get("choices") if isinstance(payload, dict) else None- for choice in choices if isinstance(choices, list) else []:- message = choice.get("message") if isinstance(choice, dict) else None- images = message.get("images") if isinstance(message, dict) else None- for image in images if isinstance(images, list) else []:- image_url = image.get("image_url") if isinstance(image, dict) else None- url = image_url.get("url") if isinstance(image_url, dict) else None+ for choice in _list_at(payload, "choices"):+ for image in _list_at(_dict_at(choice, "message"), "images"):+ url = _dict_at(image, "image_url").get("url")if isinstance(url, str) and url.strip():out.append(url.strip())return out-def _access_error_hint(- display: str, model_id: str, env_var: str, status: int, err_msg: str-) -> Optional[str]:+def _access_error_hint(display: str, model_id: str, env_var: str, status: int, err_msg: str) -> Optional[str]:"""Actionable line when an access-gated OpenAI image model is unreachable(the key is valid but the *model* needs account enablement / BYOK, so"check your key" would mislead). ``None`` when this isn't that case."""@@ -255,15 +268,11 @@ def _get_catalog(base_url: str, path: str, api_key: str, timeout: Any) -> List[Timport requestsresponse = requests.get(- f"{base_url}{path}",- headers={"Authorization": f"Bearer {api_key}"} if api_key else {},- timeout=timeout,+ f"{base_url}{path}", headers={"Authorization": f"Bearer {api_key}"} if api_key else {}, timeout=timeout,)response.raise_for_status()- body = response.json()- entries = body.get("data") if isinstance(body, dict) else Noneout: List[Tuple[str, Dict[str, Any]]] = []- for entry in entries if isinstance(entries, list) else []:+ for entry in _list_at(response.json(), "data"):model_id = entry.get("id") if isinstance(entry, dict) else Noneif isinstance(model_id, str) and model_id.strip():out.append((model_id.strip(), entry))@@ -271,8 +280,8 @@ def _get_catalog(base_url: str, path: str, api_key: str, timeout: Any) -> List[Tdef _fetch_catalog(- base_url: str, api_key: str, *, path: str, meta: Dict[str, Dict[str, Any]],- generic: str, image_output_only: bool,+ base_url: str, api_key: str, *, path: str, meta: Dict[str, Dict[str, Any]], generic: str,+ image_output_only: bool,) -> List[Dict[str, Any]]:"""Picker rows from ``GET {base_url}{path}``; raises on failure.@@ -282,11 +291,9 @@ def _fetch_catalog("""out: List[Dict[str, Any]] = []for model_id, entry in _get_catalog(base_url, path, api_key, _LIVE_TIMEOUT):- arch_raw = entry.get("architecture")- arch: Dict[str, Any] = arch_raw if isinstance(arch_raw, dict) else {}+ arch = _dict_at(entry, "architecture")if image_output_only and (- model_id.startswith(_EXCLUDED_MODEL_PREFIXES)- or "image" not in (arch.get("output_modalities") or [])+ model_id.startswith(_EXCLUDED_MODEL_PREFIXES) or "image" not in (arch.get("output_modalities") or [])):continueknown = meta.get(model_id, {})@@ -299,11 +306,6 @@ def _fetch_catalog(return out-def _image_api_model_meta(model_id: str) -> Dict[str, Any]:- """Catalog metadata for *model_id*, or permissive defaults when unknown."""- return _IMAGE_API_MODELS.get(model_id, _UNKNOWN_IMAGE_API_MODEL)--def _fetch_image_api_catalog(base_url: str, api_key: str) -> frozenset:"""Model ids served by ``GET {base_url}/images/models``, cached per base URL.@@ -325,6 +327,11 @@ def _fetch_image_api_catalog(base_url: str, api_key: str) -> frozenset:return resolved+def _image_api_model_meta(model_id: str) -> Dict[str, Any]:+ """Catalog metadata for *model_id*, or permissive defaults when unknown."""+ return _IMAGE_API_MODELS.get(model_id, _UNKNOWN_IMAGE_API_MODEL)++def _select_surface(model_id: str, base_url: str, api_key: str, config_key: str) -> str:"""``"images"`` or ``"chat"`` for *model_id*.@@ -354,8 +361,7 @@ def _image_api_setting(name: str, explicit: Any, config_key: str) -> Any:env_value = os.environ.get(f"{_IMAGE_API_ENV_PREFIX}{name.upper()}", "").strip()if env_value:return env_value- scoped = _load_image_gen_config().get(config_key)- value = scoped.get(name) if isinstance(scoped, dict) else None+ value = _dict_at(_load_image_gen_config(), config_key).get(name)return (value.strip() or None) if isinstance(value, str) else value@@ -401,8 +407,8 @@ def _pick_exact_aspect_ratio(def _image_api_enum(- name: str, explicit: Any, meta: Dict[str, Any], config_key: str, notes: List[str],- *, meta_key: Optional[str] = None,+ name: str, explicit: Any, meta: Dict[str, Any], config_key: str, notes: List[str], *,+ meta_key: Optional[str] = None,) -> Optional[str]:"""Resolve an enum knob and drop it when this model doesn't accept it."""value = _image_api_setting(name, explicit, config_key)@@ -420,8 +426,8 @@ def _image_api_enum(def _build_image_api_payload(- *, model_id: str, prompt: str, semantic_aspect: str, references: List[str],- config_key: str, kwargs: Dict[str, Any],+ *, model_id: str, prompt: str, semantic_aspect: str, references: List[str], config_key: str,+ kwargs: Dict[str, Any],) -> Tuple[Dict[str, Any], List[str]]:"""Assemble the ``/images/generations`` body: ``(payload, notes)``.@@ -437,32 +443,24 @@ def _build_image_api_payload(ratio = _pick_exact_aspect_ratio(semantic_aspect, meta, forced_ratio, notes)if ratio:payload["aspect_ratio"] = ratio-- for enum_name, meta_key in (- ("resolution", "resolutions"), ("quality", None), ("background", None), ("output_format", None),- ):+ for enum_name, meta_key in _IMAGE_API_ENUMS:value = _image_api_enum(enum_name, kwargs.get(enum_name), meta, config_key, notes, meta_key=meta_key)if value:payload[enum_name] = value-- for name, gate, clamp in (- ("output_compression", "compression", lambda v: max(0, min(100, v))),- ("seed", "seed", lambda v: v),- ):+ for name, gate, clamp in _IMAGE_API_INTS:value = _coerce_int(_image_api_setting(name, kwargs.get(name), config_key))- if value is not None:- if meta.get(gate):- payload[name] = clamp(value)- else:- notes.append(f"'{name}' is not supported by this model; dropped")-+ if value is None:+ continue+ if meta.get(gate):+ payload[name] = clamp(value)+ else:+ notes.append(f"'{name}' is not supported by this model; dropped")count = _coerce_int(_image_api_setting("n", kwargs.get("n"), config_key))if count is not None and count > 1:max_n = int(meta.get("max_n") or 1)if count > max_n:notes.append(f"'n={count}' exceeds this model's cap of {max_n}; clamped")payload["n"] = max(1, min(count, max_n))-if references:max_refs = int(meta.get("max_refs") or 0)usable = references[:max_refs] if max_refs else []@@ -485,26 +483,24 @@ def _extract_image_api_error(response: Any, fallback: str) -> str:try:body = response.json()except Exception: # noqa: BLE001 - non-JSON error body- text = getattr(response, "text", "") or ""- return text[:300] or fallback+ return (getattr(response, "text", "") or "")[:300] or fallbackerror = body.get("error") if isinstance(body, dict) else Noneif isinstance(error, str) and error.strip():return error.strip()if not isinstance(error, dict):return json.dumps(body)[:300] if body else fallback-message = error.get("message")if error.get("name") == "ZodError" and isinstance(message, str):try:issues = json.loads(message)except Exception: # noqa: BLE001return message[:300]- parts: List[str] = []- for issue in issues if isinstance(issues, list) else []:- if isinstance(issue, dict):- field = ".".join(str(p) for p in (issue.get("path") or [])) or "request"- parts.append(f"{field}: {issue.get('message') or 'invalid'}")+ parts = [+ f"{'.'.join(str(p) for p in (issue.get('path') or [])) or 'request'}: "+ f"{issue.get('message') or 'invalid'}"+ for issue in (issues if isinstance(issues, list) else []) if isinstance(issue, dict)+ ]return "; ".join(parts)[:400] or message[:300]if isinstance(message, str) and message.strip():return message.strip()[:300]@@ -538,9 +534,7 @@ def _image_api_extra(payload: Dict[str, Any], saved: List[str], usable_refs: List[str], notes: List[str], body: Any) -> Dict[str, Any]:"""Success ``extra`` for an Image API result (knobs sent, extra images, usage)."""- extra: Dict[str, Any] = {- "endpoint": "images/generations", "exact_aspect_ratio": payload.get("aspect_ratio"),- }+ extra: Dict[str, Any] = {"endpoint": "images/generations", "exact_aspect_ratio": payload.get("aspect_ratio")}extra.update({key: payload[key] for key in _IMAGE_API_EXTRA_KEYS if key in payload})if len(saved) > 1:extra["additional_images"] = saved[1:]@@ -548,12 +542,11 @@ def _image_api_extra(extra["reference_images_used"] = len(payload.get("input_references") or [])if notes:extra["notes"] = notes- usage = body.get("usage") if isinstance(body, dict) else None- if isinstance(usage, dict):- if isinstance(usage.get("cost"), (int, float)):- extra["cost_usd"] = usage["cost"]- if isinstance(usage.get("total_tokens"), int):- extra["total_tokens"] = usage["total_tokens"]+ usage = _dict_at(body, "usage")+ if isinstance(usage.get("cost"), (int, float)):+ extra["cost_usd"] = usage["cost"]+ if isinstance(usage.get("total_tokens"), int):+ extra["total_tokens"] = usage["total_tokens"]return extra@@ -587,17 +580,13 @@ class OpenRouterCompatImageProvider(ImageGenProvider):def display_name(self) -> str:return self._display- def _resolve_runtime(self) -> Dict[str, Any]:- from hermes_cli.runtime_provider import resolve_runtime_provider-- return resolve_runtime_provider(requested=self._runtime_name)-def _credentials(self) -> Tuple[str, str]:"""``(api_key, base_url)`` — either may be ``""``; raises on resolution failure."""- runtime = self._resolve_runtime()+ from hermes_cli.runtime_provider import resolve_runtime_provider++ runtime = resolve_runtime_provider(requested=self._runtime_name)return (- str(runtime.get("api_key") or "").strip(),- str(runtime.get("base_url") or "").strip().rstrip("/"),+ str(runtime.get("api_key") or "").strip(), str(runtime.get("base_url") or "").strip().rstrip("/"),)def is_available(self) -> bool:@@ -612,10 +601,9 @@ class OpenRouterCompatImageProvider(ImageGenProvider):# report the cap of the model that would service the next call.max_refs = _MAX_REFERENCE_IMAGESif self._supports_image_api:- chain = self._resolve_model_chain()- resolved = chain[0] if chain else ""+ resolved = self._resolve_model_chain()[0]if resolved in _IMAGE_API_MODELS:- max_refs = int(_image_api_model_meta(resolved).get("max_refs") or max_refs)+ max_refs = int(_IMAGE_API_MODELS[resolved].get("max_refs") or max_refs)return {"modalities": ["text", "image"], "max_reference_images": max_refs}def list_models(self) -> List[Dict[str, Any]]:@@ -628,13 +616,11 @@ class OpenRouterCompatImageProvider(ImageGenProvider):"""merged: Dict[str, Dict[str, Any]] = {}if self._supports_image_api:- for entry in self._image_api_live_models():- merged[entry["id"]] = entry+ merged = {entry["id"]: entry for entry in self._image_api_live_models()}for entry in self._live_models():merged.setdefault(entry["id"], entry)if merged:return sorted(merged.values(), key=lambda m: (_MODEL_PRIORITY.get(m["id"], 2), m["id"]))-models = [{"id": model_id, **meta} for model_id, meta in _KNOWN_MODEL_META.items()]if self._supports_image_api:models.extend(@@ -661,16 +647,14 @@ class OpenRouterCompatImageProvider(ImageGenProvider):def _image_api_live_models(self) -> List[Dict[str, Any]]:return self._cached_catalog(- "_image_api_models_cache", path="/images/models", meta=_IMAGE_API_MODELS,+ "_image_api_models_cache", "Image API catalog", path="/images/models", meta=_IMAGE_API_MODELS,generic="Image API model (from live OpenRouter catalog)", image_output_only=False,- label="Image API catalog",)def _live_models(self) -> List[Dict[str, Any]]:return self._cached_catalog(- "_live_models_cache", path="/models", meta=_KNOWN_MODEL_META,+ "_live_models_cache", "image model catalog", path="/models", meta=_KNOWN_MODEL_META,generic="Image-output model (from live OpenRouter catalog)", image_output_only=True,- label="image model catalog",)def default_model(self) -> Optional[str]:@@ -692,8 +676,7 @@ class OpenRouterCompatImageProvider(ImageGenProvider):if isinstance(candidate, str) and candidate.strip():return [candidate.strip()]cfg = _load_image_gen_config()- scoped = cfg.get(self._config_key)- for candidate in (scoped.get("model") if isinstance(scoped, dict) else None, cfg.get("model")):+ for candidate in (_dict_at(cfg, self._config_key).get("model"), cfg.get("model")):if isinstance(candidate, str) and candidate.strip():return [candidate.strip()]return list(_DEFAULT_MODEL_CHAIN)@@ -733,7 +716,6 @@ class OpenRouterCompatImageProvider(ImageGenProvider):+ ", ".join(unreadable) + ". Refusing to silently fall back to text-to-image.","io_error",)-payload, notes = _build_image_api_payload(model_id=model_id, prompt=prompt, semantic_aspect=semantic_aspect,references=usable_refs, config_key=self._config_key, kwargs=kwargs,@@ -760,9 +742,7 @@ class OpenRouterCompatImageProvider(ImageGenProvider):if failure.kind != "http":return _fail(failure.error, failure.error_type, retryable=failure.kind == "timeout")status, message = failure.status, failure.message- logger.error(- "%s image API generation failed (%s) on %s: %s", self._name, status, model_id, message,- )+ logger.error("%s image API generation failed (%s) on %s: %s", self._name, status, model_id, message)# 401/403 first so one account-level rejection does not get two# different error_types depending on where in the chain it landed.if status in (401, 403):@@ -776,8 +756,7 @@ class OpenRouterCompatImageProvider(ImageGenProvider):)return _fail(failure.error, "api_error", retryable=status in _IMAGE_API_FALLBACK_STATUSES)- entries = body.get("data") if isinstance(body, dict) else None- entries = [e for e in entries if isinstance(e, dict)] if isinstance(entries, list) else []+ entries = [e for e in _list_at(body, "data") if isinstance(e, dict)]if not entries:return _fail(f"{self._display} returned no image data for '{model_id}'.", "empty_response", retryable=True,@@ -790,8 +769,8 @@ class OpenRouterCompatImageProvider(ImageGenProvider):if not saved:return _fail(f"{self._display} response carried neither b64_json nor url.", "empty_response")return success_response(- image=saved[0], model=model_id, prompt=prompt, aspect_ratio=semantic_aspect,- provider=self._name, modality="image" if usable_refs else "text",+ image=saved[0], model=model_id, prompt=prompt, aspect_ratio=semantic_aspect, provider=self._name,+ modality="image" if usable_refs else "text",extra=_image_api_extra(payload, saved, usable_refs, notes, body),)@@ -809,21 +788,19 @@ class OpenRouterCompatImageProvider(ImageGenProvider):"image_config": {"aspect_ratio": _ASPECT_RATIOS.get(aspect, "1:1")},}result, failure = post_json(- f"{base_url}/chat/completions", headers=headers, payload=payload,- timeout=_REQUEST_TIMEOUT, label=self._display,+ f"{base_url}/chat/completions", headers=headers, payload=payload, timeout=_REQUEST_TIMEOUT,+ label=self._display,)if failure is not None:- if failure.kind == "http":- logger.error(- "%s image gen failed (%d) on %s: %s", self._name, failure.status, model_id, failure.message,- )- hint = _access_error_hint(- self._display, model_id, self._model_env_var, failure.status, failure.message- )- if hint:- return fail(hint, "model_access"), "unavailable"- return fail(failure.error, "api_error"), None- return fail(failure.error, failure.error_type), "timed out" if failure.kind == "timeout" else None+ if failure.kind != "http":+ reason = "timed out" if failure.kind == "timeout" else None+ return fail(failure.error, failure.error_type), reason+ status, message = failure.status, failure.message+ logger.error("%s image gen failed (%d) on %s: %s", self._name, status, model_id, message)+ hint = _access_error_hint(self._display, model_id, self._model_env_var, status, message)+ if hint:+ return fail(hint, "model_access"), "unavailable"+ return fail(failure.error, "api_error"), Noneimages = _extract_images(result)if not images:@@ -866,7 +843,7 @@ class OpenRouterCompatImageProvider(ImageGenProvider):aspect = resolve_aspect_ratio(aspect_ratio)# The pet generator passes local paths via ``reference_images``; the# generic tool surface uses ``image_url`` / ``reference_image_urls``.- references: List[str] = [str(ref) for ref in kwargs.get("reference_images") or []]+ references = [str(ref) for ref in kwargs.get("reference_images") or []]if image_url:references.append(str(image_url))references.extend(str(ref) for ref in reference_image_urls or [])@@ -875,13 +852,7 @@ class OpenRouterCompatImageProvider(ImageGenProvider):part = _to_image_url_part(ref)if part:content.append({"type": "image_url", "image_url": {"url": part}})- headers = {- "Authorization": f"Bearer {api_key}",- "Content-Type": "application/json",- # OpenRouter attribution headers (harmless against Nous Portal).- "HTTP-Referer": "https://github.com/NousResearch/hermes-agent",- "X-Title": "Hermes Agent",- }+ headers = {"Authorization": f"Bearer {api_key}", **_ATTRIBUTION_HEADERS}last_error: Optional[Dict[str, Any]] = Nonefor i, model_id in enumerate(model_chain):@@ -903,7 +874,9 @@ class OpenRouterCompatImageProvider(ImageGenProvider):)if outcome.get("success") or reason is None or i == len(model_chain) - 1:return outcome- logger.info("%s model %s %s; retrying with fallback %s", self._name, model_id, reason, model_chain[i + 1])+ logger.info(+ "%s model %s %s; retrying with fallback %s", self._name, model_id, reason, model_chain[i + 1],+ )last_error = outcomereturn last_error or error_response(@@ -916,28 +889,19 @@ class OpenRouterCompatImageProvider(ImageGenProvider):def _build_providers() -> List[OpenRouterCompatImageProvider]:return [OpenRouterCompatImageProvider(- provider_name="openrouter",- display_name="OpenRouter",- runtime_name="openrouter",- config_key="openrouter",- model_env_var="OPENROUTER_IMAGE_MODEL",- supports_image_api=True,+ provider_name="openrouter", display_name="OpenRouter", runtime_name="openrouter",+ config_key="openrouter", model_env_var="OPENROUTER_IMAGE_MODEL", supports_image_api=True,setup_schema={"name": "OpenRouter (image)","badge": "paid","tag": "Gemini Flash Image, gpt-image-2, Krea 2, Qwen Image 3 & more via OpenRouter; uses OPENROUTER_API_KEY","env_vars": [{- "key": "OPENROUTER_API_KEY",- "prompt": "OpenRouter API key",- "url": "https://openrouter.ai/keys",+ "key": "OPENROUTER_API_KEY", "prompt": "OpenRouter API key", "url": "https://openrouter.ai/keys",}],},),OpenRouterCompatImageProvider(- provider_name="nous",- display_name="Nous Portal",- runtime_name="nous",- config_key="nous",+ provider_name="nous", display_name="Nous Portal", runtime_name="nous", config_key="nous",model_env_var="NOUS_IMAGE_MODEL",setup_schema={"name": "Nous Portal (image)",