The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(image_gen): compact _common and openai-codex docstrings/comments (WHYs kept)
Tekniumf564cba6252f
diff --git a/plugins/image_gen/_common.py b/plugins/image_gen/_common.pyindex 385baf3f009..c43faf778ae 100644--- a/plugins/image_gen/_common.py+++ b/plugins/image_gen/_common.py@@ -1,9 +1,6 @@-"""Shared helpers for the bundled ``image_gen`` provider plugins.--Providers are loaded by path (``hermes_plugins.image_gen__<name>``) and resolve-this module through the repo root on ``sys.path``. Not a plugin itself: the-scanner only looks at directories.-"""+"""Shared helpers for the bundled ``image_gen`` provider plugins. Providers are loaded by path+(``hermes_plugins.image_gen__<name>``) and resolve this via the repo root on ``sys.path``;+not a plugin itself (the scanner only looks at directories)."""from __future__ import annotations@@ -17,12 +14,10 @@ from agent.image_gen_provider import (logger = logging.getLogger(__name__)-# OpenAI-style ``size`` strings for the three semantic aspect ratios, shared by-# every OpenAI-compatible ``images.generations`` backend.+# OpenAI-style ``size`` per semantic aspect, shared by every OpenAI-compatible backend.OPENAI_SIZES: Dict[str, str] = {"landscape": "1536x1024", "square": "1024x1024", "portrait": "1024x1536"}-# gpt-image-2 quality tiers as three virtual model ids (same API model,-# different ``quality`` knob) so the picker works like any multi-model backend.+# gpt-image-2 quality tiers as virtual model ids (same API model, different ``quality`` knob).GPT_IMAGE_2_API_MODEL = "gpt-image-2"GPT_IMAGE_2_DEFAULT = "gpt-image-2-medium"GPT_IMAGE_2_TIERS: Dict[str, Dict[str, Any]] = {@@ -78,12 +73,8 @@ def resolve_static_model(explicit: Optional[str] = None, include_top_level: bool = True,config: Optional[Dict[str, Any]] = None,) -> Tuple[str, Dict[str, Any]]:- """Pick ``(model_id, meta)`` from a fixed catalog.-- Precedence (first *known* id wins; unknown ids fall through rather than- error): explicit caller override → ``env_var`` → ``image_gen.<config_key>.model``- → top-level ``image_gen.model`` (when ``include_top_level``) → ``default``.- """+ """``(model_id, meta)`` from a fixed catalog; first *known* id wins (unknown ids fall through):+ explicit → ``env_var`` → ``image_gen.<config_key>.model`` → ``image_gen.model`` → ``default``."""if isinstance(explicit, str) and explicit.strip() in models:return explicit.strip(), models[explicit.strip()]env_override = os.environ.get(env_var)@@ -116,8 +107,7 @@ def catalog_rows(fields: Iterable[str] = ("display", "speed", "strengths", "price"), *,price: Optional[str] = None,) -> List[Dict[str, Any]]:- """Picker rows: ``id`` plus ``fields`` from each meta (missing ``display`` →- model id, other fields → ``""``); ``price`` overrides the per-model value."""+ """Picker rows: ``id`` + ``fields`` (missing ``display`` → id, else ``""``); ``price`` overrides."""rows = []for model_id, meta in models.items():row: Dict[str, Any] = {"id": model_id}@@ -139,13 +129,9 @@ def api_key_setup_schema(class StaticImageGenProvider(ImageGenProvider):- """Identity + picker surface driven by class attributes.-- Subclasses set ``provider_id`` / ``label``; a fixed catalog sets ``models``- (+ ``default_model_id``, optional ``price`` override and ``catalog_fields``);- single-env-var auth sets ``setup`` (kwargs for :func:`api_key_setup_schema`).- Dynamic-catalog or custom-setup providers override the relevant method.- """+ """Identity + picker surface from class attributes: ``provider_id``/``label``; fixed catalog via+ ``models`` (+ ``default_model_id``, ``price``, ``catalog_fields``); single-env-var auth via+ ``setup`` (kwargs for :func:`api_key_setup_schema`). Dynamic providers override methods."""provider_id: strlabel: str@@ -205,12 +191,8 @@ def materialize_image(b64: Optional[str], url: Optional[str], *, prefix: str, label: str, provider: str, model: str,prompt: str, aspect: str, log: logging.Logger = logger, on_url_fail: Optional[Callable[[Exception], None]] = None,) -> Tuple[Optional[str], Optional[Dict[str, Any]]]:- """``(image_ref, None)`` or ``(None, error_dict)`` for a ``(b64_json, url)`` pair.-- Base64 is always cached (write failure → ``io_error``); a URL is cached- best-effort, falling back to the bare URL so a cache hiccup never destroys- a successful generation.- """+ """``(image_ref, None)`` or ``(None, error)`` for a ``(b64_json, url)`` pair. Base64 is always+ cached (write failure → ``io_error``); a URL is cached best-effort, falling back to the bare URL."""fail = error_factory(provider, aspect, model=model, prompt=prompt)if b64:try:@@ -247,9 +229,8 @@ def requests_error_message(response: Any, exc: Exception) -> str:@dataclassclass HttpFailure:- """One failed ``post_json`` attempt, pre-shaped as ``(error, error_type)``.- ``kind`` ∈ http / timeout / connection / request / invalid_json; ``message``- carries the HTTP error text (``http``) or the decode error (``invalid_json``);+ """One failed ``post_json`` attempt as ``(error, error_type)``. ``kind`` ∈ http / timeout /+ connection / request / invalid_json; ``message`` = HTTP error text or decode error;``status`` / ``response`` are set for ``http`` only."""kind: str@@ -265,12 +246,9 @@ def post_json(error_message: Callable[[Any, Exception], str] = requests_error_message,catch_request_exception: bool = False,) -> Tuple[Optional[Any], Optional[HttpFailure]]:- """POST ``payload`` and parse the JSON body: ``(body, None)`` or ``(None, failure)``.-- ``timeout`` is passed to ``requests`` verbatim; the timeout message reports- its read component. ``error_message(response, exc)`` extracts the HTTP error- text so each backend can keep its own body shape.- """+ """POST ``payload`` → ``(json_body, None)`` or ``(None, failure)``. ``timeout`` goes to ``requests``+ verbatim (message reports the read component); ``error_message(response, exc)`` extracts the+ backend-specific HTTP error text."""import requestsread_timeout = timeout[1] if isinstance(timeout, tuple) else timeoutdiff --git a/plugins/image_gen/openai-codex/__init__.py b/plugins/image_gen/openai-codex/__init__.pyindex cb85d469549..c44372c0a5e 100644--- a/plugins/image_gen/openai-codex/__init__.py+++ b/plugins/image_gen/openai-codex/__init__.py@@ -1,14 +1,13 @@-"""OpenAI image generation backend — ChatGPT/Codex OAuth variant.+"""OpenAI image generation — ChatGPT/Codex OAuth variant.-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.+Same catalog/tiers as the ``openai`` plugin (``gpt-image-2`` low/medium/high), routed+through the Codex Responses API ``image_generation`` tool, so no ``OPENAI_API_KEY`` is+needed. Output is 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 for every account, fixed by omitting tool_choice (see-``_build_responses_payload``); any remaining HTTP error must surface verbatim.+'image_generation' not found in 'tools' parameter``: that 400 is a request-shape+rejection for every account, fixed by omitting tool_choice (``_build_responses_payload``);+any remaining HTTP error must surface verbatim."""from __future__ import annotations@@ -31,9 +30,7 @@ logger = logging.getLogger(__name__)_MAX_ERROR_BODY_CHARS = 500_MODELS: Dict[str, Dict[str, Any]] = dict(GPT_IMAGE_2_TIERS)-# 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_CHAT_MODEL = "gpt-5.5" # hosts the ``image_generation`` tool call; ``API_MODEL`` does the image work_CODEX_BASE_URL = "https://chatgpt.com/backend-api/codex"_CODEX_INSTRUCTIONS = ("You are an assistant that must fulfill image generation and image editing "@@ -41,16 +38,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.+# ``input_image`` accepts raster only; the shared sniffer also knows SVG/TIFF/ICO, which the API rejects._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. Request 0 partials,-# never let a partial overwrite a final, and only deliver source=final.+# Progressive frames (partial_image_b64) saved as finals produced the "smear" failure mode:+# request 0 partials, never let a partial overwrite a final, only deliver source=final._PARTIAL_IMAGES_REQUESTED = 0-# Content-agnostic retries when the stream yields no final result.-_NONFINAL_RETRIES = 1+_NONFINAL_RETRIES = 1 # content-agnostic retries when the stream yields no final result_NO_AUTH = ("No Codex/ChatGPT OAuth credentials available. Run "@@ -58,8 +52,7 @@ _NO_AUTH = (def _summarize_error_body(body: str) -> str:- """Bounded error summary preferring parsed ``error.message`` (Codex error- payloads can carry hundreds of bytes of leading metadata)."""+ """Bounded summary preferring parsed ``error.message`` (Codex bodies carry leading metadata)."""text = body or ""try:payload = json.loads(text)@@ -78,8 +71,7 @@ def _resolve_model() -> Tuple[str, Dict[str, Any]]:def _read_codex_access_token() -> Optional[str]:- """Usable Codex OAuth token or None; ``agent.auxiliary_client`` owns expiry,- pool selection and JWT decoding."""+ """Usable Codex OAuth token or None (``agent.auxiliary_client`` owns expiry/pool/JWT)."""try:from agent.auxiliary_client import _read_codex_access_token as _reader@@ -175,13 +167,9 @@ def _normalize_input_images(def _build_responses_payload(*, prompt: str, size: str, quality: str, input_images: Optional[List[Dict[str, str]]] = None) -> Dict[str, Any]:- """Codex Responses body for an image_generation call.-- No ``tool_choice`` is sent: the Codex backend rejects every shape for- 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.- """+ """Responses body for an image_generation call. No ``tool_choice``: Codex rejects every shape+ for forcing the hosted tool (looks it up as a *function* name), so the host model decides,+ nudged by ``instructions``."""content: List[Dict[str, Any]] = [{"type": "input_text", "text": prompt}, *(input_images or [])]return {"model": _CODEX_CHAT_MODEL,@@ -202,8 +190,8 @@ def _build_responses_payload(def _extract_image_candidates(value: Any) -> Tuple[Optional[str], Optional[str]]:- """``(final_result_b64, latest_partial_b64)`` from a payload tree, tracked- separately so a partial can never overwrite a genuine final."""+ """``(final_result_b64, latest_partial_b64)`` from a payload tree; a partial never overwrites+ a final."""result_b64: Optional[str] = Nonepartial_b64: Optional[str] = None@@ -240,8 +228,7 @@ 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, so- image-generation events newer than the pinned SDK still parse."""+ """JSON payloads from an SSE response, without SDK parsing (events newer than the SDK still parse)."""event_name: Optional[str] = Nonedata_lines: List[str] = []@@ -279,12 +266,8 @@ def _iter_sse_json(response: Any):def _collect_image_b64(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 partial- is retained only when no final ever arrives; callers must not treat- partial-only as success.- """+ """Stream a Codex Responses image_generation call → ``{"b64", "source": "final"|"partial"}`` or+ ``None``. A partial is kept only when no final arrives; callers must not treat it as success."""import httpxfrom agent.codex_headers import codex_cloudflare_headers