Skip to content

The agent that grows with you

refactor(image_gen): compact krea/openai-codex/xai providers; extract krea payload builder

Tekniumbb25c3630677
diff --git a/plugins/image_gen/krea/__init__.py b/plugins/image_gen/krea/__init__.py
index 7a36a30e12b..da4ca1775f0 100644
--- a/plugins/image_gen/krea/__init__.py
+++ b/plugins/image_gen/krea/__init__.py
@@ -1,19 +1,13 @@
"""Krea image generation backend.
-Exposes Krea's ``Krea 2`` foundation image model family (Medium, Large,
-Medium Turbo) as an :class:`ImageGenProvider`.
-
-Krea's API is asynchronous: the generate endpoint returns a ``job_id`` polled
-at ``GET /jobs/{job_id}``. This provider hides that roundtrip behind the
-synchronous ``generate()`` contract: submit, poll every 2s with light backoff,
-materialise the result URL to local cache, return the usual dict.
-
-Selection precedence (first hit wins): ``model`` kwarg → ``KREA_IMAGE_MODEL``
-env → ``image_gen.krea.model`` → ``image_gen.model`` (when it's one of our
-IDs) → :data:`DEFAULT_MODEL` (``krea-2-medium``, Krea's "start here" pick).
+Exposes Krea's ``Krea 2`` family (Medium, Large, Medium Turbo) as an
+:class:`ImageGenProvider`. Krea's API is asynchronous: submit returns a
+``job_id`` polled at ``GET /jobs/{job_id}``; ``generate()`` hides that
+(submit, poll every 2s with light backoff, cache the result URL locally).
+Selection: ``model`` kwarg → ``KREA_IMAGE_MODEL`` → ``image_gen.krea.model`` →
+``image_gen.model`` (when one of our IDs) → :data:`DEFAULT_MODEL`.
Docs: https://docs.krea.ai/developers/krea-2/overview
-API: https://docs.krea.ai/api-reference/krea/krea-2-large
"""
from __future__ import annotations
@@ -81,36 +75,28 @@ DEFAULT_MODEL = "krea-2-medium"
# Hermes' 3 abstract ratios → Krea's enum (1:1, 4:3, 3:2, 16:9, 2.35:1, 4:5, 2:3, 9:16).
_ASPECT_MAP = {"landscape": "16:9", "square": "1:1", "portrait": "9:16"}
-
# Only resolution Krea currently supports.
DEFAULT_RESOLUTION = "1K"
-
-# image_style_references entries are objects ({"url", "strength"}), not bare
-# strings; a URL without explicit strength gets Krea's recommended start (range -2..2).
+# image_style_references entries are objects ({"url", "strength"}); a URL
+# without explicit strength gets Krea's recommended start (range -2..2).
_DEFAULT_STYLE_REFERENCE_STRENGTH = 0.6
_MAX_STYLE_REFERENCES = 10
-
_VALID_CREATIVITY = {"raw", "low", "medium", "high"}
-# Polling: Krea recommends 2-5s; start at 2s, back off to 5s for long jobs
-# (Large can take ~1min). Ceiling matches Krea's hosted-tool timeout of 3 min.
+# Polling: Krea recommends 2-5s; start at 2s, back off to 5s (Large can take
+# ~1min). Ceiling matches Krea's hosted-tool timeout of 3 min.
_POLL_INITIAL_INTERVAL = 2.0
_POLL_MAX_INTERVAL = 5.0
_POLL_BACKOFF = 1.3
_POLL_TIMEOUT_SECONDS = 180.0
-
-# Statuses worth retrying while polling. Everything else (401/402/403/404,
-# other 4xx) is permanent — surface it immediately instead of burning the
-# 180s deadline on a request that will never succeed.
+# Statuses worth retrying while polling; everything else (401/402/403/404,
+# other 4xx) is permanent — surface it instead of burning the 180s deadline.
_RETRYABLE_POLL_STATUSES = frozenset({408, 409, 425, 429, 500, 502, 503, 504})
-
_TERMINAL_STATES = {"completed", "failed", "cancelled"}
-# Krea Enhance — the optional ``upscale`` pass after generation ("1.5K native,
-# 4K via Enhancer" is Krea's own pipeline shape). Cheap creative enhancer, max 8K.
+# Krea Enhance — the optional ``upscale`` pass after generation (max 8K).
_ENHANCE_PATH = "/generate/enhance/krea/enhance"
_ENHANCE_SCALE_FACTOR = 2
-
_USER_AGENT = "Hermes-Agent/1.0 (krea-image-gen)"
@@ -125,8 +111,6 @@ def _krea_section() -> Dict[str, Any]:
def _resolve_model(explicit: Optional[str] = None) -> Tuple[str, Dict[str, Any]]:
- """``(model_id, meta)``: explicit → ``KREA_IMAGE_MODEL`` → ``image_gen.krea.model``
- → ``image_gen.model`` → :data:`DEFAULT_MODEL`."""
return resolve_static_model(
_MODELS, DEFAULT_MODEL, env_var="KREA_IMAGE_MODEL", config_key="krea",
explicit=explicit, config=_load_krea_config(),
@@ -136,11 +120,10 @@ def _resolve_model(explicit: Optional[str] = None) -> Tuple[str, Dict[str, Any]]
def _resolve_managed_krea_gateway():
"""Managed Krea gateway config when the user is on the managed path, else ``None``.
- Strict selection: managed when the stored ``image_gen`` selection is
- ``nous`` (or legacy ``use_gateway: true``), or on a never-configured install
- with no direct ``KREA_API_KEY``. An explicit vendor selection (``krea``,
- ``fal``, ...) pins the direct path. Never raises — plugin discovery and
- availability scans must stay robust.
+ Strict selection: managed when the stored ``image_gen`` selection is ``nous``
+ (or legacy ``use_gateway: true``), or on a never-configured install with no
+ direct ``KREA_API_KEY``. An explicit vendor selection pins the direct path.
+ Never raises — plugin discovery and availability scans must stay robust.
"""
try:
from tools.managed_tool_gateway import resolve_managed_tool_gateway
@@ -148,7 +131,6 @@ def _resolve_managed_krea_gateway():
except Exception as exc: # noqa: BLE001
logger.debug("Managed Krea gateway resolution unavailable: %s", exc)
return None
-
try:
selected = read_selection("image_gen")
except Exception: # noqa: BLE001
@@ -157,7 +139,6 @@ def _resolve_managed_krea_gateway():
return None
if selected is None and get_secret("KREA_API_KEY"):
return None
-
try:
return resolve_managed_tool_gateway("krea")
except Exception as exc: # noqa: BLE001
@@ -189,8 +170,8 @@ def _headers(auth_token: str, *, managed: bool, json_body: bool) -> Dict[str, st
headers["Content-Type"] = "application/json"
if managed:
# The gateway derives the per-generation billing idempotency boundary
- # from this header (else a body fingerprint); a fresh key per submit
- # keeps each generation a distinct billable execution.
+ # from this header; a fresh key per submit keeps each generation a
+ # distinct billable execution.
headers["x-idempotency-key"] = str(uuid.uuid4())
return headers
@@ -294,8 +275,7 @@ def _poll_krea_job(
def _extract_result_url(job: Optional[Dict[str, Any]]) -> Optional[str]:
- """First result URL from a terminal Krea job: ``result.urls[]`` per Krea's
- job-lifecycle docs, falling back to a single ``result.url``."""
+ """First result URL: ``result.urls[]`` per Krea's job docs, else ``result.url``."""
result = job.get("result") if isinstance(job, dict) else None
if not isinstance(result, dict):
return None
@@ -307,18 +287,13 @@ def _extract_result_url(job: Optional[Dict[str, Any]]) -> Optional[str]:
def _enhance_image(
- base_url: str,
- auth_token: str,
- image_url: str,
- prompt: str,
- *,
- managed: bool,
+ base_url: str, auth_token: str, image_url: str, prompt: str, *, managed: bool
) -> Optional[str]:
"""Run Krea Enhance on ``image_url``; return the enhanced URL or None.
- Best-effort: any submit/poll/result failure logs and returns ``None`` so
- the caller falls back to the original image — an upscale failure must
- never destroy an already-successful generation.
+ Best-effort: any submit/poll/result failure logs and returns ``None`` so the
+ caller falls back to the original image — an upscale failure must never
+ destroy an already-successful generation.
"""
payload: Dict[str, Any] = {
"image_url": image_url,
@@ -341,7 +316,6 @@ def _enhance_image(
if not isinstance(job_id, str) or not job_id:
logger.warning("Krea Enhance submit response missing job_id")
return None
-
job = _poll_krea_job(base_url, auth_token, job_id)
if not isinstance(job, dict) or job.get("status") in {"failed", "cancelled"}:
logger.warning("Krea Enhance job %s did not complete successfully", job_id)
@@ -352,18 +326,16 @@ def _enhance_image(
def _collect_style_refs(
image_url: Optional[str], reference_image_urls: Optional[List[str]], legacy_refs: Any
) -> List[Any]:
- """Reference images for style transfer: unified ``image_url`` +
- ``reference_image_urls`` first, then the legacy ``image_style_references``
- kwarg, whose entries may be URL strings or Krea ref objects (passed through
- verbatim). Strings are deduped in order; capped at Krea's limit of 10."""
+ """Style-transfer references: unified ``image_url`` + ``reference_image_urls``
+ first, then the legacy ``image_style_references`` kwarg (URL strings or Krea
+ ref objects, passed through). Strings deduped in order; capped at 10."""
refs: List[Any] = collect_source_images(image_url, reference_image_urls)
- if isinstance(legacy_refs, list):
- for ref in legacy_refs:
- if isinstance(ref, str):
- if ref.strip():
- refs.append(ref.strip())
- elif ref:
- refs.append(ref)
+ for ref in legacy_refs if isinstance(legacy_refs, list) else []:
+ if isinstance(ref, str):
+ if ref.strip():
+ refs.append(ref.strip())
+ elif ref:
+ refs.append(ref)
seen: set = set()
deduped: List[Any] = []
for r in refs:
@@ -375,6 +347,29 @@ def _collect_style_refs(
return deduped[:_MAX_STYLE_REFERENCES]
+def _build_payload(
+ prompt: str, krea_ar: str, creativity: str, style_refs: List[Any], kwargs: Dict[str, Any]
+) -> Dict[str, Any]:
+ payload: Dict[str, Any] = {
+ "prompt": prompt, "aspect_ratio": krea_ar, "resolution": DEFAULT_RESOLUTION, "creativity": creativity,
+ }
+ if isinstance(kwargs.get("seed"), int):
+ payload["seed"] = kwargs["seed"]
+ styles, moodboards = kwargs.get("styles"), kwargs.get("moodboards")
+ if isinstance(styles, list) and styles:
+ payload["styles"] = styles
+ if style_refs:
+ # Krea requires objects ({"url", "strength"}) — a bare string yields a
+ # 422 "Expected object, received string". Object refs pass through.
+ payload["image_style_references"] = [
+ {"url": ref, "strength": _DEFAULT_STYLE_REFERENCE_STRENGTH} if isinstance(ref, str) else ref
+ for ref in style_refs
+ ]
+ if isinstance(moodboards, list) and moodboards:
+ payload["moodboards"] = moodboards[:1] # Krea caps at 1 moodboard per request.
+ return payload
+
+
class KreaImageGenProvider(ImageGenProvider):
"""Krea ``Krea 2`` foundation image model backend (Medium + Large)."""
@@ -387,8 +382,8 @@ class KreaImageGenProvider(ImageGenProvider):
return "Krea"
def is_available(self) -> bool:
- # Direct key OR the managed Nous gateway (Nous Subscription), so portal
- # users without a Krea key can still reach Krea 2.
+ # Direct key OR the managed Nous gateway, so portal users without a
+ # Krea key can still reach Krea 2.
return bool(get_secret("KREA_API_KEY")) or _managed_krea_gateway_ready()
def list_models(self) -> List[Dict[str, Any]]:
@@ -405,8 +400,6 @@ class KreaImageGenProvider(ImageGenProvider):
)
def capabilities(self) -> Dict[str, Any]:
- # Reference-guided generation via image_style_references (up to 10) plus
- # the opt-in Enhance upscale pass.
return {
"modalities": ["text", "image"],
"max_reference_images": _MAX_STYLE_REFERENCES,
@@ -425,18 +418,13 @@ class KreaImageGenProvider(ImageGenProvider):
prompt = (prompt or "").strip()
aspect = resolve_aspect_ratio(aspect_ratio)
krea_ar = _ASPECT_MAP.get(aspect, "1:1")
-
- style_refs = _collect_style_refs(
- image_url, reference_image_urls, kwargs.get("image_style_references")
- )
- modality = "image" if style_refs else "text"
-
+ style_refs = _collect_style_refs(image_url, reference_image_urls, kwargs.get("image_style_references"))
if not prompt:
return prompt_required_error("krea", aspect)
- # Managed Nous gateway (Nous Subscription) owns the shared Krea
- # credential and meters per generation, so the caller token is the Nous
- # access token; otherwise the direct Krea API with a BYO ``KREA_API_KEY``.
+ # Managed Nous gateway (Nous Subscription) owns the shared Krea credential
+ # and meters per generation, so the caller token is the Nous access
+ # token; otherwise the direct Krea API with a BYO ``KREA_API_KEY``.
managed = _resolve_managed_krea_gateway()
if managed is not None:
base_url = managed.gateway_origin.rstrip("/")
@@ -457,55 +445,24 @@ class KreaImageGenProvider(ImageGenProvider):
model_id, meta = _resolve_model(kwargs.get("model"))
creativity = _resolve_creativity(kwargs.get("creativity"))
fail = error_factory("krea", aspect, model=model_id, prompt=prompt)
-
- styles = kwargs.get("styles")
- moodboards = kwargs.get("moodboards")
- styles = styles if isinstance(styles, list) and styles else None
- moodboards = moodboards if isinstance(moodboards, list) and moodboards else None
+ payload = _build_payload(prompt, krea_ar, creativity, style_refs, kwargs)
# The managed gateway only prices base text-to-image and URL style
# references; LoRAs and moodboards are rejected there, so fail fast
# with guidance instead of a raw 400.
if managed is not None:
- for present, what, arg in (
- (styles, "trained styles (LoRAs)", "styles"),
- (moodboards, "moodboards", "moodboards"),
- ):
- if present:
+ for what, arg in (("trained styles (LoRAs)", "styles"), ("moodboards", "moodboards")):
+ if arg in payload:
return fail(
f"Managed Krea (Nous Subscription) does not support {what}. "
f"Set KREA_API_KEY to use Krea directly, or omit `{arg}`.",
"unsupported_argument",
)
- payload: Dict[str, Any] = {
- "prompt": prompt,
- "aspect_ratio": krea_ar,
- "resolution": DEFAULT_RESOLUTION,
- "creativity": creativity,
- }
- seed = kwargs.get("seed")
- if isinstance(seed, int):
- payload["seed"] = seed
- if styles:
- payload["styles"] = styles
- if style_refs:
- # Krea requires objects ({"url", "strength"}) — a bare string yields
- # a 422 "Expected object, received string". Object refs pass through.
- payload["image_style_references"] = [
- {"url": ref, "strength": _DEFAULT_STYLE_REFERENCE_STRENGTH}
- if isinstance(ref, str) else ref
- for ref in style_refs
- ]
- if moodboards:
- # Krea currently caps at 1 moodboard per request.
- payload["moodboards"] = moodboards[:1]
-
# 1. Submit job.
- submit_url = f"{base_url}/generate/image/krea/krea-2/{meta['path']}"
try:
response = requests.post(
- submit_url,
+ f"{base_url}/generate/image/krea/krea-2/{meta['path']}",
headers=_headers(auth_token, managed=managed is not None, json_body=True),
json=payload, timeout=30,
)
@@ -538,19 +495,16 @@ class KreaImageGenProvider(ImageGenProvider):
return fail("Krea submit timed out (30s)", "timeout")
except requests.ConnectionError as exc:
return fail(f"Krea connection error: {exc}", "connection_error")
-
try:
submit_body = response.json()
except Exception as exc: # noqa: BLE001
return fail(f"Krea returned invalid JSON on submit: {exc}", "invalid_response")
-
job_id = submit_body.get("job_id")
if not isinstance(job_id, str) or not job_id:
return fail("Krea submit response missing job_id", "invalid_response")
- # 2. Poll for completion. Polling is bound to the same principal at the
- # gateway, so the managed path polls the gateway's ``/jobs/{id}`` with
- # the Nous token (404 on cross-user/unknown jobs).
+ # 2. Poll. Polling is bound to the same principal at the gateway, so the
+ # managed path polls the gateway's ``/jobs/{id}`` with the Nous token.
poll_errors: List[Dict[str, Any]] = []
def poll_error(kind: str, detail: Any) -> Dict[str, Any]:
@@ -576,15 +530,14 @@ class KreaImageGenProvider(ImageGenProvider):
return fail("Krea returned non-dict job body", "invalid_response")
# 3. Terminal — extract result.
- last_status = job.get("status")
- if last_status == "failed":
- err = (job.get("result") or {}).get("error") if isinstance(job.get("result"), dict) else None
+ result = job.get("result")
+ if job.get("status") == "failed":
+ err = result.get("error") if isinstance(result, dict) else None
return fail(f"Krea job {job_id} failed: {err or 'unknown error'}", "api_error")
- if last_status == "cancelled":
+ if job.get("status") == "cancelled":
return fail(f"Krea job {job_id} was cancelled", "cancelled")
- if not isinstance(job.get("result"), dict):
+ if not isinstance(result, dict):
return fail("Krea job completed but result was missing", "empty_response")
-
result_image_url = _extract_result_url(job)
if result_image_url is None:
return fail("Krea result contained no image URL", "empty_response")
@@ -596,13 +549,9 @@ class KreaImageGenProvider(ImageGenProvider):
upscale_requested = kwargs.get("upscale")
if not isinstance(upscale_requested, bool):
cfg_upscale = _krea_section().get("upscale")
- upscale_requested = (
- cfg_upscale if isinstance(cfg_upscale, bool) else bool(meta.get("upscale", False))
- )
+ upscale_requested = cfg_upscale if isinstance(cfg_upscale, bool) else bool(meta.get("upscale", False))
if upscale_requested:
- enhanced_url = _enhance_image(
- base_url, auth_token, result_image_url, prompt, managed=managed is not None,
- )
+ enhanced_url = _enhance_image(base_url, auth_token, result_image_url, prompt, managed=managed is not None)
if enhanced_url:
result_image_url = enhanced_url
upscaled = True
@@ -614,8 +563,7 @@ class KreaImageGenProvider(ImageGenProvider):
image_ref = str(save_url_image(result_image_url, prefix=f"krea_{model_id}"))
except Exception as exc: # noqa: BLE001
logger.warning(
- "Krea image URL %s could not be cached (%s); falling back to bare URL.",
- result_image_url, exc,
+ "Krea image URL %s could not be cached (%s); falling back to bare URL.", result_image_url, exc,
)
image_ref = result_image_url
@@ -630,15 +578,9 @@ class KreaImageGenProvider(ImageGenProvider):
extra["upscale_factor"] = _ENHANCE_SCALE_FACTOR
if isinstance(job.get("completed_at"), str):
extra["completed_at"] = job["completed_at"]
-
return success_response(
- image=image_ref,
- model=model_id,
- prompt=prompt,
- aspect_ratio=aspect,
- provider="krea",
- modality=modality,
- extra=extra,
+ image=image_ref, model=model_id, prompt=prompt, aspect_ratio=aspect, provider="krea",
+ modality="image" if style_refs else "text", extra=extra,
)
diff --git a/plugins/image_gen/openai-codex/__init__.py b/plugins/image_gen/openai-codex/__init__.py
index e13fe72278e..2e32d15ddb5 100644
--- a/plugins/image_gen/openai-codex/__init__.py
+++ b/plugins/image_gen/openai-codex/__init__.py
@@ -1,21 +1,14 @@
"""OpenAI image generation backend — ChatGPT/Codex OAuth variant.
-Same model catalog and tier semantics as the ``openai`` plugin (``gpt-image-2``
-at low/medium/high quality), but routed through the Codex Responses API
-``image_generation`` tool instead of ``images.generate``, so users already
-authenticated with Codex/ChatGPT need no separate ``OPENAI_API_KEY``.
-
-Tier precedence: ``OPENAI_IMAGE_MODEL`` env → ``image_gen.openai-codex.model``
-→ ``image_gen.model`` (when it's one of our tier IDs) → :data:`DEFAULT_MODEL`.
-Output is saved as PNG under ``$HERMES_HOME/cache/images/``; source images for
-editing are sent as Responses ``input_image`` content parts.
+Same catalog and tier semantics as the ``openai`` plugin (``gpt-image-2`` at
+low/medium/high), routed through the Codex Responses API ``image_generation``
+tool, so Codex/ChatGPT users need no separate ``OPENAI_API_KEY``. Output is
+saved as PNG; source images travel as Responses ``input_image`` parts.
Do NOT reintroduce an "account capability" classifier keyed on ``Tool choice
'image_generation' not found in 'tools' parameter``: that HTTP 400 is a
-request-shape rejection emitted for every account (the Codex backend resolves
-tool_choice as a function-tool name), not an entitlement problem. It is fixed
-by omitting tool_choice (see ``_build_responses_payload``); any remaining HTTP
-error must surface verbatim so it stays diagnosable.
+request-shape rejection for every account, fixed by omitting tool_choice (see
+``_build_responses_payload``); any remaining HTTP error must surface verbatim.
"""
from __future__ import annotations
@@ -49,11 +42,10 @@ from plugins.image_gen._common import (
logger = logging.getLogger(__name__)
_MAX_ERROR_BODY_CHARS = 500
-
_MODELS: Dict[str, Dict[str, Any]] = dict(GPT_IMAGE_2_TIERS)
-# Codex Responses surface used for the request. The chat model only hosts the
-# ``image_generation`` tool call; the image work is done by ``API_MODEL``.
+# The chat model only hosts the ``image_generation`` tool call; the image work
+# is done by ``API_MODEL``.
_CODEX_CHAT_MODEL = "gpt-5.5"
_CODEX_BASE_URL = "https://chatgpt.com/backend-api/codex"
_CODEX_INSTRUCTIONS = (
@@ -63,16 +55,13 @@ _CODEX_INSTRUCTIONS = (
_MAX_REFERENCE_IMAGES = 16
_MAX_INPUT_IMAGE_BYTES = 25 * 1024 * 1024
-# gpt-image-2's ``input_image`` accepts raster formats only. The shared sniffer
-# also recognizes SVG/TIFF/ICO, which the API rejects server-side — gate to this
-# allowlist so unsupported inputs fail locally instead of as an opaque HTTP 400.
+# gpt-image-2's ``input_image`` accepts raster formats only; the shared sniffer
+# also recognizes SVG/TIFF/ICO, which the API rejects server-side.
_ACCEPTED_INPUT_MIME = frozenset({"image/png", "image/jpeg", "image/gif", "image/webp"})
# Progressive preview frames (partial_image_b64) are intermediate renders;
-# saving them as finals produced the "smear" failure mode. Defense in depth:
-# request 0 partials, never let a partial overwrite a final in the extractor,
-# and only deliver source=final from generate(). Live streams may still emit a
-# partial event even with 0 — fine as long as only a final ``result`` is saved.
+# saving them as finals produced the "smear" failure mode. Request 0 partials,
+# never let a partial overwrite a final, and only deliver source=final.
_PARTIAL_IMAGES_REQUESTED = 0
# Content-agnostic retries when the stream yields no final result.
_NONFINAL_RETRIES = 1
@@ -84,11 +73,8 @@ _NO_AUTH = (
def _summarize_error_body(body: str) -> str:
- """Bounded error summary preferring parsed ``error.message``.
-
- A blind head-truncation of the raw body can cut the actual message off —
- Codex error payloads sometimes carry hundreds of bytes of leading metadata.
- """
+ """Bounded error summary preferring parsed ``error.message`` (Codex error
+ payloads can carry hundreds of bytes of leading metadata)."""
text = body or ""
try:
payload = json.loads(text)
@@ -102,29 +88,23 @@ def _summarize_error_body(body: str) -> str:
def _resolve_model() -> Tuple[str, Dict[str, Any]]:
- """Decide which tier to use and return ``(model_id, meta)``."""
- return resolve_static_model(
- _MODELS, DEFAULT_MODEL, env_var="OPENAI_IMAGE_MODEL", config_key="openai-codex"
- )
+ return resolve_static_model(_MODELS, DEFAULT_MODEL, env_var="OPENAI_IMAGE_MODEL", config_key="openai-codex")
def _read_codex_access_token() -> Optional[str]:
- """Usable Codex OAuth token or None; the canonical reader in
- ``agent.auxiliary_client`` owns expiry, pool selection and JWT decoding."""
+ """Usable Codex OAuth token or None; ``agent.auxiliary_client`` owns expiry,
+ pool selection and JWT decoding."""
try:
from agent.auxiliary_client import _read_codex_access_token as _reader
token = _reader()
- if isinstance(token, str) and token.strip():
- return token.strip()
- return None
+ return token.strip() if isinstance(token, str) and token.strip() else None
except Exception as exc:
logger.debug("Could not resolve Codex access token: %s", exc)
return None
def _sniff_image_mime(raw: bytes) -> Optional[str]:
- """Raster MIME from magic bytes (shared sniffer), gated to :data:`_ACCEPTED_INPUT_MIME`."""
from agent.image_routing import _sniff_mime_from_bytes
mime = _sniff_mime_from_bytes(raw)
@@ -142,7 +122,6 @@ def _encode_input_image(raw: bytes, too_big: str, unsupported: str) -> str:
def _data_url_to_input_image_url(value: str) -> str:
- """Validate and canonicalize a data:image URL for Responses input_image."""
if "," not in value:
raise ValueError("Image data URL is missing a comma separator")
header, data = value.split(",", 1)
@@ -157,7 +136,6 @@ def _data_url_to_input_image_url(value: str) -> str:
def _local_image_to_data_url(value: str) -> str:
- """Read a local image path and return a validated data:image URL."""
try:
from agent.file_safety import get_read_block_error
@@ -168,7 +146,6 @@ def _local_image_to_data_url(value: str) -> str:
raise
except Exception as exc:
logger.debug("Codex image input read guard unavailable: %s", exc)
-
path = Path(os.path.expanduser(value)).resolve()
if not path.is_file():
raise ValueError(f"Image input path does not exist or is not a file: {value}")
@@ -197,31 +174,23 @@ def _to_input_image_part(value: str) -> Dict[str, str]:
def _normalize_input_images(
- image_url: Optional[str],
- reference_image_urls: Optional[List[str]],
+ image_url: Optional[str], reference_image_urls: Optional[List[str]]
) -> List[Dict[str, str]]:
- """Collect primary + reference images as ordered Responses content parts."""
values = collect_source_images(image_url, reference_image_urls, limit=_MAX_REFERENCE_IMAGES)
return [_to_input_image_part(value) for value in values]
def _build_responses_payload(
- *,
- prompt: str,
- size: str,
- quality: str,
- input_images: Optional[List[Dict[str, str]]] = None,
+ *, prompt: str, size: str, quality: str, input_images: Optional[List[Dict[str, str]]] = None
) -> Dict[str, Any]:
- """Build the Codex Responses request body for an image_generation call.
+ """Codex Responses body for an image_generation call.
No ``tool_choice`` is sent: the Codex backend rejects every shape for
- forcing the hosted ``image_generation`` tool (it looks tool_choice up as a
- *function* name), so letting the host model decide — nudged by
- ``instructions`` — is the only accepted shape.
+ forcing the hosted tool (it looks tool_choice up as a *function* name), so
+ letting the host model decide — nudged by ``instructions`` — is the only
+ accepted shape.
"""
- content: List[Dict[str, Any]] = [{"type": "input_text", "text": prompt}]
- if input_images:
- content.extend(input_images)
+ content: List[Dict[str, Any]] = [{"type": "input_text", "text": prompt}, *(input_images or [])]
return {
"model": _CODEX_CHAT_MODEL,
"store": False,
@@ -241,11 +210,8 @@ def _build_responses_payload(
def _extract_image_candidates(value: Any) -> Tuple[Optional[str], Optional[str]]:
- """Return ``(final_result_b64, latest_partial_b64)`` from a payload tree.
-
- Tracked separately so a partial can never overwrite a genuine final, even
- when both coexist in the same event payload.
- """
+ """``(final_result_b64, latest_partial_b64)`` from a payload tree, tracked
+ separately so a partial can never overwrite a genuine final."""
result_b64: Optional[str] = None
partial_b64: Optional[str] = None
@@ -276,7 +242,7 @@ def _extract_image_b64(value: Any) -> Optional[str]:
def _png_pixel_size(raw: bytes) -> Optional[str]:
- """Return ``"{w}x{h}"`` for a PNG payload, or None if not a PNG IHDR."""
+ """``"{w}x{h}"`` for a PNG payload, or None if not a PNG IHDR."""
import struct
if len(raw) < 24 or raw[:8] != b"\x89PNG\r\n\x1a\n" or raw[12:16] != b"IHDR":
@@ -286,11 +252,8 @@ def _png_pixel_size(raw: bytes) -> Optional[str]:
def _iter_sse_json(response: Any):
- """Yield JSON payloads from an SSE response without OpenAI SDK parsing.
-
- The Codex backend can emit image-generation events newer than the pinned
- SDK understands; raw SSE parsing stays tolerant of those shape changes.
- """
+ """Yield JSON payloads from an SSE response without OpenAI SDK parsing, so
+ image-generation events newer than the pinned SDK still parse."""
event_name: Optional[str] = None
data_lines: List[str] = []
@@ -300,9 +263,7 @@ def _iter_sse_json(response: Any):
event_name = None
return None
raw = "\n".join(data_lines).strip()
- event = event_name
- event_name = None
- data_lines = []
+ event, event_name, data_lines = event_name, None, []
if not raw or raw == "[DONE]":
return None
payload = json.loads(raw)
@@ -318,32 +279,23 @@ def _iter_sse_json(response: Any):
payload = flush()
if payload is not None:
yield payload
- continue
- if line.startswith(":"):
- continue
- if line.startswith("event:"):
+ elif line.startswith("event:"):
event_name = line[len("event:"):].strip()
elif line.startswith("data:"):
data_lines.append(line[len("data:"):].lstrip())
-
payload = flush()
if payload is not None:
yield payload
def _collect_image_b64(
- token: str,
- *,
- prompt: str,
- size: str,
- quality: str,
- input_images: Optional[List[Dict[str, str]]] = None,
+ token: str, *, prompt: str, size: str, quality: str, input_images: Optional[List[Dict[str, str]]] = None
) -> Optional[Dict[str, str]]:
"""Stream a Codex Responses image_generation call.
- Returns ``{"b64": ..., "source": "final"|"partial"}`` or ``None``. A
- progressive partial is retained only when no final result ever arrives;
- callers must not treat partial-only as success.
+ Returns ``{"b64": ..., "source": "final"|"partial"}`` or ``None``. A partial
+ is retained only when no final ever arrives; callers must not treat
+ partial-only as success.
"""
import httpx
from agent.codex_headers import codex_cloudflare_headers
@@ -354,9 +306,7 @@ def _collect_image_b64(
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
})
- payload = _build_responses_payload(
- prompt=prompt, size=size, quality=quality, input_images=input_images,
- )
+ payload = _build_responses_payload(prompt=prompt, size=size, quality=quality, input_images=input_images)
timeout = httpx.Timeout(300.0, connect=30.0, read=300.0, write=30.0, pool=30.0)
final_b64: Optional[str] = None
@@ -373,11 +323,8 @@ def _collect_image_b64(
) from exc
for event in _iter_sse_json(response):
result_b64, event_partial = _extract_image_candidates(event)
- if result_b64:
- final_b64 = result_b64
- if event_partial:
- partial_b64 = event_partial
-
+ final_b64 = result_b64 or final_b64
+ partial_b64 = event_partial or partial_b64
if final_b64:
return {"b64": final_b64, "source": "final"}
if partial_b64:
@@ -424,8 +371,6 @@ class OpenAICodexImageGenProvider(ImageGenProvider):
}
def capabilities(self) -> Dict[str, Any]:
- # Source/reference images travel as `input_image` content parts; keep
- # this honest so the dynamic schema encourages identity-preserving edits.
return {"modalities": ["text", "image"], "max_reference_images": _MAX_REFERENCE_IMAGES}
def generate(
@@ -439,14 +384,11 @@ class OpenAICodexImageGenProvider(ImageGenProvider):
) -> Dict[str, Any]:
prompt = (prompt or "").strip()
aspect = resolve_aspect_ratio(aspect_ratio)
-
if not prompt:
return prompt_required_error("openai-codex", aspect)
-
token = _read_codex_access_token()
if not token:
return error_factory("openai-codex", aspect)(_NO_AUTH, "auth_required")
-
try:
import httpx # noqa: F401
except ImportError:
@@ -458,7 +400,6 @@ class OpenAICodexImageGenProvider(ImageGenProvider):
size = size_for(aspect)
fail = error_factory("openai-codex", aspect, model=tier_id, prompt=prompt)
attempts = _NONFINAL_RETRIES + 1
-
try:
input_images = _normalize_input_images(image_url, reference_image_urls)
except Exception as exc:
@@ -468,8 +409,7 @@ class OpenAICodexImageGenProvider(ImageGenProvider):
collected: Optional[Dict[str, str]] = None
for attempt in range(attempts):
collected = _collect_image_b64(
- token, prompt=prompt, size=size, quality=meta["quality"],
- input_images=input_images or None,
+ token, prompt=prompt, size=size, quality=meta["quality"], input_images=input_images or None,
)
if collected and collected.get("source") == "final" and collected.get("b64"):
break
@@ -480,8 +420,7 @@ class OpenAICodexImageGenProvider(ImageGenProvider):
else "no image_generation_call result"
)
logger.warning(
- "Codex image stream ended with %s (attempt %s/%s); "
- "retrying once before failing closed.",
+ "Codex image stream ended with %s (attempt %s/%s); retrying once before failing closed.",
kind, attempt + 1, attempts,
)
except Exception as exc:
@@ -493,10 +432,8 @@ class OpenAICodexImageGenProvider(ImageGenProvider):
f"Codex response contained no image_generation_call result after {attempts} attempt(s)",
"empty_response",
)
-
image_source = collected.get("source") or "unknown"
b64 = collected["b64"]
-
# Never deliver a progressive-only frame as success (smeared previews).
if image_source != "final":
try:
@@ -510,10 +447,10 @@ class OpenAICodexImageGenProvider(ImageGenProvider):
if pixel_hint:
detail = f"{detail} partial_pixel_size={pixel_hint}."
err = fail(detail, "incomplete_image")
- err["image_source"] = image_source
- err["requested_size"] = size
- err["partial_pixel_size"] = pixel_hint
- err["nonfinal_retries"] = _NONFINAL_RETRIES
+ err.update(
+ image_source=image_source, requested_size=size,
+ partial_pixel_size=pixel_hint, nonfinal_retries=_NONFINAL_RETRIES,
+ )
return err
try:
@@ -521,13 +458,8 @@ class OpenAICodexImageGenProvider(ImageGenProvider):
saved_path = save_b64_image(b64, prefix=f"openai_codex_{tier_id}")
except Exception as exc:
return fail(f"Could not save image to cache: {exc}", "io_error")
-
return success_response(
- image=str(saved_path),
- model=tier_id,
- prompt=prompt,
- aspect_ratio=aspect,
- provider="openai-codex",
+ image=str(saved_path), model=tier_id, prompt=prompt, aspect_ratio=aspect, provider="openai-codex",
modality="image" if input_images else "text",
extra={
"size": size,
diff --git a/plugins/image_gen/xai/__init__.py b/plugins/image_gen/xai/__init__.py
index ecd40cea9ab..3c9abf83b40 100644
--- a/plugins/image_gen/xai/__init__.py
+++ b/plugins/image_gen/xai/__init__.py
@@ -1,11 +1,11 @@
"""xAI image generation backend.
Exposes xAI's ``grok-imagine-image`` models as an :class:`ImageGenProvider`:
-text-to-image (``/v1/images/generations``, several aspect ratios, 1K/2K) and
-image editing (``/v1/images/edits``), base64 output saved to cache.
+text-to-image (``/v1/images/generations``) and image editing
+(``/v1/images/edits``), base64 output saved to cache.
-Selection precedence (first hit wins): ``model`` kwarg → ``XAI_IMAGE_MODEL``
-env → ``image_gen.xai.model`` → :data:`DEFAULT_MODEL`.
+Selection: ``model`` kwarg → ``XAI_IMAGE_MODEL`` → ``image_gen.xai.model`` →
+:data:`DEFAULT_MODEL`.
"""
from __future__ import annotations
@@ -64,16 +64,13 @@ DEFAULT_MODEL = "grok-imagine-image"
# xAI documents the quality model as the edit-capable baseline.
_EDIT_FALLBACK_MODEL = "grok-imagine-image-quality"
-# Live catalog cache: (models_dict, fetched_monotonic). xAI's
-# ``/image-generation-models`` endpoint is the source of truth so newly
-# released Imagine models appear in the picker without a code change; the
-# static ``_MODELS`` table is the offline fallback and supplies curated
-# speed/strengths text for the models we know about.
+# Live catalog cache: (models_dict, fetched_monotonic). ``/image-generation-models``
+# is the source of truth so new Imagine models appear without a code change;
+# ``_MODELS`` is the offline fallback and supplies curated text for known ids.
_LIVE_CACHE: Optional[Tuple[Dict[str, Dict[str, Any]], float]] = None
_LIVE_CACHE_TTL = 300.0
_LIVE_TIMEOUT = 10.0
-# xAI aspect ratios (more options than FAL/OpenAI)
_XAI_ASPECT_RATIOS = {
"landscape": "16:9",
"square": "1:1",
@@ -87,6 +84,8 @@ _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")
def _base_url(creds: Dict[str, Any]) -> str:
@@ -94,11 +93,8 @@ def _base_url(creds: Dict[str, Any]) -> str:
def _fetch_live_models() -> Dict[str, Dict[str, Any]]:
- """Fetch image models from xAI's ``/image-generation-models`` endpoint.
-
- Returns ``{model_id: {"input_modalities": [...], "aliases": [...]}}``.
- Raises on any failure — callers treat that as "use the static table".
- """
+ """``{model_id: {"input_modalities", "aliases"}}`` from ``/image-generation-models``;
+ raises on any failure (callers fall back to the static table)."""
creds = resolve_xai_http_credentials()
api_key = str(creds.get("api_key") or "").strip()
if not api_key:
@@ -110,18 +106,14 @@ def _fetch_live_models() -> Dict[str, Dict[str, Any]]:
)
response.raise_for_status()
payload = response.json()
- entries = payload.get("models") or payload.get("data") or []
out: Dict[str, Dict[str, Any]] = {}
- for entry in entries:
- if not isinstance(entry, dict):
- continue
- model_id = entry.get("id") or entry.get("name")
- if not isinstance(model_id, str) or not model_id.strip():
- continue
- out[model_id.strip()] = {
- "input_modalities": entry.get("input_modalities") or [],
- "aliases": entry.get("aliases") or [],
- }
+ for entry in payload.get("models") or payload.get("data") or []:
+ 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 [],
+ }
return out
@@ -142,25 +134,18 @@ def _live_models() -> Dict[str, Dict[str, Any]]:
def _catalog() -> Dict[str, Dict[str, Any]]:
- """Merged model catalog: live endpoint IDs + curated static metadata.
-
- Known models keep their curated display/speed/strengths; models xAI ships
- later still show up (with generic metadata) so users can pick them the day
- they launch. Curated entries the live list momentarily omits are kept;
- static table alone when the API is unreachable.
- """
+ """Merged catalog: live ids + curated static metadata. Unknown live models get
+ generic text; curated entries the live list omits are kept; static table
+ alone when the API is unreachable."""
live = _live_models()
if not live:
return dict(_MODELS)
merged: Dict[str, Dict[str, Any]] = {}
for model_id in live:
meta = _MODELS.get(model_id) or {
- "display": model_id,
- "speed": "",
- "strengths": "New xAI Imagine model (from live xAI catalog)",
+ "display": model_id, "speed": "", "strengths": "New xAI Imagine model (from live xAI catalog)",
}
- merged[model_id] = dict(meta)
- merged[model_id]["input_modalities"] = live[model_id].get("input_modalities") or []
+ merged[model_id] = {**meta, "input_modalities": live[model_id].get("input_modalities") or []}
for model_id, meta in _MODELS.items():
merged.setdefault(model_id, dict(meta))
return merged
@@ -176,11 +161,8 @@ def _configured_model() -> Optional[str]:
def _resolve_model(caller_model: Optional[str] = None) -> Tuple[str, Dict[str, Any]]:
- """Return ``(model_id, meta)``: caller kwarg → ``XAI_IMAGE_MODEL`` → config → default.
-
- Every candidate is validated against the merged live+static catalog, so a
- newly released xAI model is selectable the day it appears in the live catalog.
- """
+ """``(model_id, meta)``: caller kwarg → ``XAI_IMAGE_MODEL`` → config → default,
+ each validated against the merged live+static catalog."""
catalog = _catalog()
for candidate in (caller_model, os.environ.get("XAI_IMAGE_MODEL"), _configured_model()):
if candidate and candidate in catalog:
@@ -193,9 +175,8 @@ def _resolve_edit_model(caller_model: Optional[str] = None) -> str:
image input is honored; otherwise the documented quality baseline."""
catalog = _catalog()
explicit = caller_model or os.environ.get("XAI_IMAGE_MODEL") or _configured_model()
- if explicit and explicit in catalog:
- if "image" in (catalog[explicit].get("input_modalities") or []):
- return explicit
+ if explicit and explicit in catalog and "image" in (catalog[explicit].get("input_modalities") or []):
+ return explicit
return _EDIT_FALLBACK_MODEL
@@ -205,18 +186,14 @@ def _resolve_resolution() -> str:
def _xai_image_field(source: str) -> Dict[str, str]:
- """Build the xAI ``image`` field for an edit request.
-
- ``/v1/images/edits`` accepts a public HTTPS URL or a base64 data URI; local
- file paths are read and encoded into a ``data:`` URI.
- """
+ """xAI ``image`` field for an edit request: public HTTPS URL or base64 data
+ URI; local paths are read and encoded into a ``data:`` URI."""
source = source.strip()
- if source.lower().startswith(("http://", "https://", "data:")):
+ if source.lower().startswith(_REMOTE_PREFIXES):
return {"url": source, "type": "image_url"}
import base64
- # Shared credential-read guard before reading local bytes (same boundary
- # the OpenAI / OpenRouter / Codex image providers apply).
+ # Shared credential-read guard before reading local bytes.
from agent.file_safety import raise_if_read_blocked
raise_if_read_blocked(source)
@@ -225,8 +202,7 @@ def _xai_image_field(source: str) -> Dict[str, str]:
ext = (os.path.splitext(source)[1].lstrip(".") or "png").lower()
if ext == "jpg":
ext = "jpeg"
- b64 = base64.b64encode(raw).decode("utf-8")
- return {"url": f"data:image/{ext};base64,{b64}", "type": "image_url"}
+ return {"url": f"data:image/{ext};base64,{base64.b64encode(raw).decode('utf-8')}", "type": "image_url"}
class XAIImageGenProvider(ImageGenProvider):
@@ -248,13 +224,9 @@ class XAIImageGenProvider(ImageGenProvider):
def get_setup_schema(self) -> Dict[str, Any]:
# Auth resolution is delegated to the shared ``xai_grok`` post_setup hook
- # (``hermes_cli/tools_config.py``), identical to the TTS / video-gen
- # entries, so every xAI service shows the same OAuth-or-API-key choice.
+ # so every xAI service shows the same OAuth-or-API-key choice.
storage_notice = xai_storage_notice_text("image_gen")
- tag = (
- "grok-imagine-image - text-to-image & image editing; uses xAI "
- "Grok OAuth or XAI_API_KEY"
- )
+ tag = "grok-imagine-image - text-to-image & image editing; uses xAI Grok OAuth or XAI_API_KEY"
if storage_notice:
tag += f". {storage_notice}"
return {
@@ -282,12 +254,9 @@ class XAIImageGenProvider(ImageGenProvider):
reference_image_urls: Optional[List[str]] = None,
**kwargs: Any,
) -> Dict[str, Any]:
- """Text-to-image via ``/v1/images/generations``, or image editing via
- ``/v1/images/edits`` when source images are supplied.
-
- Editing uses a JSON body (xAI does not support the OpenAI SDK's
- multipart ``images.edit()``) and an image-input-capable model.
- """
+ """Text-to-image, or image editing via ``/v1/images/edits`` (JSON body —
+ xAI does not support the SDK's multipart ``images.edit()``) when source
+ images are supplied."""
creds = resolve_xai_http_credentials()
api_key = str(creds.get("api_key") or "").strip()
provider_name = str(creds.get("provider") or "xai").strip() or "xai"
@@ -300,23 +269,21 @@ class XAIImageGenProvider(ImageGenProvider):
model_id, meta = _resolve_model(kwargs.get("model"))
aspect = resolve_aspect_ratio(aspect_ratio)
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",
+ 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
field = "image_url" if index == 0 and image_url and image_url.strip() == source else "reference_image_urls"
- if not source.lower().startswith(("http://", "https://", "data:")):
- if not Path(source).expanduser().is_file():
- 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",
- )
+ 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",
+ )
is_edit = bool(source_images)
headers = {
@@ -325,27 +292,20 @@ class XAIImageGenProvider(ImageGenProvider):
"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",
- )
+ storage_options = build_xai_storage_options("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")
if is_edit:
- # An explicit user selection that accepts image input (e.g.
- # grok-imagine-image-2.0) is honored; otherwise the quality baseline.
model_id = _resolve_edit_model(kwargs.get("model"))
try:
image_fields = [_xai_image_field(source) for source in source_images]
except Exception as exc:
- return edit_fail(
- f"Could not load source image for editing: {exc}", "io_error", model=model_id,
- )
+ 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}
- if len(image_fields) == 1:
- payload["image"] = image_fields[0]
- else:
- payload["images"] = image_fields
+ payload["image" if len(image_fields) == 1 else "images"] = (
+ image_fields[0] if len(image_fields) == 1 else image_fields
+ )
endpoint_url = f"{base_url}/images/edits"
else:
payload = {
@@ -359,34 +319,27 @@ class XAIImageGenProvider(ImageGenProvider):
payload["storage_options"] = storage_options
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",
- )
+ result, failure = post_json(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)
return fail(failure.error, failure.error_type)
- # xAI returns data[0].b64_json, data[0].url, and optionally
- # data[0].file_output when storage_options were requested.
+ # data[0] carries b64_json / url, plus file_output when storage_options were requested.
data = result.get("data", [])
if not data:
return fail("xAI returned no image data", "empty_response")
-
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
-
if public_url:
image_ref = public_url
else:
- # grok-imagine-image URLs (``imgen.x.ai/xai-tmp-*``) 404 within
- # minutes; materialise locally so downstream consumers (Telegram
- # send_photo …) get a stable path.
+ # grok-imagine-image URLs (``imgen.x.ai/xai-tmp-*``) 404 within minutes;
+ # materialise locally so downstream consumers get a stable path.
image_ref, err = materialize_image(
- first.get("b64_json"), first.get("url"),
- prefix=f"xai_{model_id}", label="xAI", provider="xai",
+ first.get("b64_json"), first.get("url"), prefix=f"xai_{model_id}", label="xAI", provider="xai",
model=model_id, prompt=prompt, aspect=aspect, log=logger,
)
if err:
@@ -399,22 +352,12 @@ class XAIImageGenProvider(ImageGenProvider):
extra["storage_notice"] = storage_notice
if public_url:
extra["public_url"] = public_url
- for key in (
- "filename", "expires_at", "public_url_expires_at", "public_url_error", "storage_error",
- ):
- if key in file_output:
- extra[key] = file_output[key]
+ extra.update({key: file_output[key] for key in _FILE_OUTPUT_EXTRA_KEYS if key in file_output})
if result.get("usage"):
extra["usage"] = result["usage"]
-
return success_response(
- image=image_ref,
- model=model_id,
- prompt=prompt,
- aspect_ratio=aspect,
- provider="xai",
- modality="image" if is_edit else "text",
- extra=extra,
+ image=image_ref, model=model_id, prompt=prompt, aspect_ratio=aspect, provider="xai",
+ modality="image" if is_edit else "text", extra=extra,
)