Skip to content

The agent that grows with you

refactor(image_gen/xai): extract _check_source_images phase, drop config/time wrappers, compact tables

Tekniumc2af7b2a8572
diff --git a/plugins/image_gen/xai/__init__.py b/plugins/image_gen/xai/__init__.py
index 107af84fb8d..65e3012d768 100644
--- a/plugins/image_gen/xai/__init__.py
+++ b/plugins/image_gen/xai/__init__.py
@@ -12,6 +12,7 @@ from __future__ import annotations
import logging
import os
+import time
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
@@ -29,16 +30,14 @@ logger = logging.getLogger(__name__)
_MODELS: Dict[str, Dict[str, Any]] = {
"grok-imagine-image": {
- "display": "Grok Imagine Image", "speed": "~5-10s", "strengths": "Fast, high-quality"
+ "display": "Grok Imagine Image", "speed": "~5-10s", "strengths": "Fast, high-quality",
},
"grok-imagine-image-2.0": {
- "display": "Grok Imagine Image 2.0",
- "speed": "~10-20s",
+ "display": "Grok Imagine Image 2.0", "speed": "~10-20s",
"strengths": "Typography/layout-aware; legible small text; strongest quality.",
},
"grok-imagine-image-quality": {
- "display": "Grok Imagine Image (Quality)",
- "speed": "~10-20s",
+ "display": "Grok Imagine Image (Quality)", "speed": "~10-20s",
"strengths": "Higher fidelity / detail; slower than the standard model.",
},
}
@@ -55,20 +54,17 @@ _LIVE_CACHE_TTL = 300.0
_LIVE_TIMEOUT = 10.0
_XAI_ASPECT_RATIOS = {
- "landscape": "16:9",
- "square": "1:1",
- "portrait": "9:16",
- "4:3": "4:3",
- "3:4": "3:4",
- "3:2": "3:2",
- "2:3": "2:3",
+ "landscape": "16:9", "square": "1:1", "portrait": "9:16",
+ "4:3": "4:3", "3:4": "3:4", "3:2": "3:2", "2:3": "2:3",
}
_XAI_RESOLUTIONS = {"1k", "2k"}
DEFAULT_RESOLUTION = "1k"
_MAX_SOURCE_IMAGES = 3
_REQUEST_TIMEOUT = 120
_REMOTE_PREFIXES = ("http://", "https://", "data:")
-_FILE_OUTPUT_EXTRA_KEYS = ("filename", "expires_at", "public_url_expires_at", "public_url_error", "storage_error")
+_FILE_OUTPUT_EXTRA_KEYS = (
+ "filename", "expires_at", "public_url_expires_at", "public_url_error", "storage_error",
+)
def _base_url(creds: Dict[str, Any]) -> str:
@@ -93,8 +89,7 @@ def _fetch_live_models() -> Dict[str, Dict[str, Any]]:
model_id = entry.get("id") or entry.get("name") if isinstance(entry, dict) else None
if isinstance(model_id, str) and model_id.strip():
out[model_id.strip()] = {
- "input_modalities": entry.get("input_modalities") or [],
- "aliases": entry.get("aliases") or [],
+ "input_modalities": entry.get("input_modalities") or [], "aliases": entry.get("aliases") or [],
}
return out
@@ -102,8 +97,6 @@ def _fetch_live_models() -> Dict[str, Dict[str, Any]]:
def _live_models() -> Dict[str, Dict[str, Any]]:
"""Cached live catalog (``{}`` when unreachable)."""
global _LIVE_CACHE
- import time
-
if _LIVE_CACHE is not None and time.monotonic() - _LIVE_CACHE[1] < _LIVE_CACHE_TTL:
return _LIVE_CACHE[0]
try:
@@ -133,12 +126,8 @@ def _catalog() -> Dict[str, Dict[str, Any]]:
return merged
-def _load_xai_config() -> Dict[str, Any]:
- return load_image_gen_config("xai")
-
-
def _configured_model() -> Optional[str]:
- value = _load_xai_config().get("model")
+ value = load_image_gen_config("xai").get("model")
return value if isinstance(value, str) else None
@@ -163,7 +152,7 @@ def _resolve_edit_model(caller_model: Optional[str] = None) -> str:
def _resolve_resolution() -> str:
- res = _load_xai_config().get("resolution")
+ res = load_image_gen_config("xai").get("resolution")
return res if isinstance(res, str) and res in _XAI_RESOLUTIONS else DEFAULT_RESOLUTION
@@ -187,6 +176,26 @@ def _xai_image_field(source: str) -> Dict[str, str]:
return {"url": f"data:image/{ext};base64,{base64.b64encode(raw).decode('utf-8')}", "type": "image_url"}
+def _check_source_images(
+ source_images: List[str], image_url: Optional[str], fail: Any
+) -> Optional[Dict[str, Any]]:
+ """Edit-request guard: at most 3 sources, each a remote URL/data URI or an existing local file."""
+ if len(source_images) > _MAX_SOURCE_IMAGES:
+ return fail(
+ f"xAI image editing supports at most {_MAX_SOURCE_IMAGES} source images", "too_many_references",
+ )
+ for index, source in enumerate(source_images):
+ if source.lower().startswith(_REMOTE_PREFIXES) or Path(source).expanduser().is_file():
+ continue
+ is_primary = index == 0 and image_url and image_url.strip() == source
+ field = "image_url" if is_primary else "reference_image_urls"
+ return fail(
+ f"{field} must be a public HTTPS URL or data URI "
+ "(e.g. the `image`/`public_url` from a prior Imagine result)",
+ "invalid_image_url")
+ return None
+
+
class XAIImageGenProvider(StaticImageGenProvider):
"""xAI ``grok-imagine-image`` backend."""
@@ -201,8 +210,7 @@ class XAIImageGenProvider(StaticImageGenProvider):
def default_model(self) -> Optional[str]:
# First live/static catalog row (inherited ImageGenProvider behaviour).
- models = self.list_models()
- return models[0].get("id") if models else None
+ return next(iter(_catalog()), None)
def get_setup_schema(self) -> Dict[str, Any]:
# Auth resolution is delegated to the shared ``xai_grok`` post_setup hook
@@ -212,19 +220,13 @@ class XAIImageGenProvider(StaticImageGenProvider):
if storage_notice:
tag += f". {storage_notice}"
return {
- "name": "xAI Grok Imagine (image)",
- "badge": "paid",
- "tag": tag,
- "env_vars": [],
- "post_setup": "xai_grok",
+ "name": "xAI Grok Imagine (image)", "badge": "paid", "tag": tag, "env_vars": [], "post_setup": "xai_grok",
}
def capabilities(self) -> Dict[str, Any]:
# /v1/images/edits accepts up to 3 total source images.
return {
- "modalities": ["text", "image"],
- "max_reference_images": 2,
- "max_source_images": _MAX_SOURCE_IMAGES,
+ "modalities": ["text", "image"], "max_reference_images": 2, "max_source_images": _MAX_SOURCE_IMAGES,
}
def generate(
@@ -248,29 +250,19 @@ class XAIImageGenProvider(StaticImageGenProvider):
xai_res = _resolve_resolution()
source_images = collect_source_images(image_url, reference_image_urls)
edit_fail = error_factory(provider_name, aspect, model=_EDIT_FALLBACK_MODEL, prompt=prompt)
- if len(source_images) > _MAX_SOURCE_IMAGES:
- return edit_fail(
- f"xAI image editing supports at most {_MAX_SOURCE_IMAGES} source images", "too_many_references",
- )
- for index, source in enumerate(source_images):
- if source.lower().startswith(_REMOTE_PREFIXES) or Path(source).expanduser().is_file():
- continue
- is_primary = index == 0 and image_url and image_url.strip() == source
- field = "image_url" if is_primary else "reference_image_urls"
- return edit_fail(
- f"{field} must be a public HTTPS URL or data URI "
- "(e.g. the `image`/`public_url` from a prior Imagine result)",
- "invalid_image_url")
+ err = _check_source_images(source_images, image_url, edit_fail)
+ if err:
+ return err
is_edit = bool(source_images)
headers = {
- "Authorization": f"Bearer {api_key}",
- "Content-Type": "application/json",
+ "Authorization": f"Bearer {api_key}", "Content-Type": "application/json",
"User-Agent": hermes_xai_user_agent(),
}
base_url = _base_url(creds)
storage_options = build_xai_storage_options(
- "image_gen", filename_prefix="hermes-xai-image", extension="png")
+ "image_gen", filename_prefix="hermes-xai-image", extension="png",
+ )
storage_notice = maybe_mark_xai_storage_notice_seen("image_gen")
storage_cfg = read_xai_imagine_storage_config("image_gen")
@@ -281,14 +273,14 @@ class XAIImageGenProvider(StaticImageGenProvider):
except Exception as exc:
return edit_fail(f"Could not load source image for editing: {exc}", "io_error", model=model_id)
payload: Dict[str, Any] = {"model": model_id, "prompt": prompt}
- payload["image" if len(image_fields) == 1 else "images"] = (
- image_fields[0] if len(image_fields) == 1 else image_fields)
+ if len(image_fields) == 1:
+ payload["image"] = image_fields[0]
+ else:
+ payload["images"] = image_fields
endpoint_url = f"{base_url}/images/edits"
else:
payload = {
- "model": model_id,
- "prompt": prompt,
- "aspect_ratio": _XAI_ASPECT_RATIOS.get(aspect, "1:1"),
+ "model": model_id, "prompt": prompt, "aspect_ratio": _XAI_ASPECT_RATIOS.get(aspect, "1:1"),
"resolution": xai_res,
}
endpoint_url = f"{base_url}/images/generations"
@@ -297,7 +289,8 @@ class XAIImageGenProvider(StaticImageGenProvider):
fail = error_factory(provider_name, aspect, model=model_id, prompt=prompt)
result, failure = post_json(
- endpoint_url, headers=headers, payload=payload, timeout=_REQUEST_TIMEOUT, label="xAI")
+ endpoint_url, headers=headers, payload=payload, timeout=_REQUEST_TIMEOUT, label="xAI",
+ )
if failure:
if failure.kind == "http":
logger.error("xAI image gen failed (%d): %s", failure.status, failure.message)
@@ -310,7 +303,8 @@ class XAIImageGenProvider(StaticImageGenProvider):
first = data[0]
file_output = first.get("file_output") if isinstance(first, dict) else None
file_output = file_output if isinstance(file_output, dict) else {}
- public_url = file_output.get("public_url") if isinstance(file_output.get("public_url"), str) else None
+ public_url = file_output.get("public_url")
+ public_url = public_url if isinstance(public_url, str) else None
if public_url:
image_ref = public_url
else: