Skip to content

The agent that grows with you

fix(image-gen): stop reporting the Codex tool_choice 400 as an account limit

teknium1064b6e40c51c
diff --git a/plugins/image_gen/openai-codex/__init__.py b/plugins/image_gen/openai-codex/__init__.py
index e4e7cd0fc09..2cee3360516 100644
--- a/plugins/image_gen/openai-codex/__init__.py
+++ b/plugins/image_gen/openai-codex/__init__.py
@@ -40,30 +40,43 @@ from agent.image_gen_provider import (
logger = logging.getLogger(__name__)
-class CodexImageGenerationUnsupportedError(RuntimeError):
- """The active Codex account cannot use the hosted image tool."""
-
-
-_IMAGE_GENERATION_UNAVAILABLE_MESSAGE = (
- "Image generation is not enabled for the current Codex account. "
- "Switch the image provider to OpenAI API key, FAL, or xAI."
-)
-_IMAGE_GENERATION_UNSUPPORTED_ERROR = (
- "Tool choice 'image_generation' not found in 'tools' parameter."
-)
-
-
-def _is_image_generation_unsupported_error(status_code: int, body: str) -> bool:
- """Match only Codex's account-capability rejection for the image tool."""
- if status_code != 400:
- return False
+# NOTE: 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 (the Codex backend resolves tool_choice as
+# a function-tool name and never recognizes hosted-tool entries) — it is
+# emitted for every account, including accounts where image generation works.
+# A previous version of this file translated that 400 into "Image generation is
+# not enabled for the current Codex account. Switch the image provider to
+# OpenAI API key, FAL, or xAI.", which reported a universal bug in our own
+# payload as the user's entitlement problem and sent people away from a
+# provider that was never actually tried. The request-shape bug is fixed by
+# omitting tool_choice (see ``_build_responses_payload``); any remaining HTTP
+# error must surface verbatim so it stays diagnosable. See issues #19505,
+# #49008 and #31335.
+
+_MAX_ERROR_BODY_CHARS = 500
+
+
+def _summarize_error_body(body: str) -> str:
+ """Return a bounded, information-preserving summary of an error body.
+
+ Prefers the parsed ``error.message`` field, because a blind head-truncation
+ of the raw body can cut the actual message off entirely — Codex error
+ payloads sometimes carry hundreds of bytes of leading metadata, so
+ ``body[:500]`` yielded a wall of padding and no diagnosis. Falls back to a
+ truncated raw body for non-JSON responses.
+ """
+ text = body or ""
try:
- payload = json.loads(body)
+ payload = json.loads(text)
error = payload.get("error") if isinstance(payload, dict) else None
message = error.get("message") if isinstance(error, dict) else None
+ if isinstance(message, str) and message.strip():
+ return message.strip()[:_MAX_ERROR_BODY_CHARS]
except (TypeError, ValueError):
- message = body
- return isinstance(message, str) and message.strip() == _IMAGE_GENERATION_UNSUPPORTED_ERROR
+ pass
+ return text[:_MAX_ERROR_BODY_CHARS]
+
# ---------------------------------------------------------------------------
@@ -423,15 +436,9 @@ def _collect_image_b64(
response.raise_for_status()
except httpx.HTTPStatusError as exc:
exc.response.read()
- full_body = exc.response.text
- if _is_image_generation_unsupported_error(
- exc.response.status_code,
- full_body,
- ):
- raise CodexImageGenerationUnsupportedError(full_body) from exc
- body = full_body[:500]
raise RuntimeError(
- f"Codex Responses API returned HTTP {exc.response.status_code}: {body}"
+ f"Codex Responses API returned HTTP {exc.response.status_code}: "
+ f"{_summarize_error_body(exc.response.text)}"
) from exc
for event in _iter_sse_json(response):
found = _extract_image_b64(event)
@@ -578,19 +585,6 @@ class OpenAICodexImageGenProvider(ImageGenProvider):
quality=meta["quality"],
input_images=input_images or None,
)
- except CodexImageGenerationUnsupportedError:
- logger.debug(
- "Codex account does not expose image generation",
- exc_info=True,
- )
- return error_response(
- error=_IMAGE_GENERATION_UNAVAILABLE_MESSAGE,
- error_type="capability_unsupported",
- provider="openai-codex",
- model=tier_id,
- prompt=prompt,
- aspect_ratio=aspect,
- )
except Exception as exc:
logger.debug("Codex image generation failed", exc_info=True)
return error_response(
diff --git a/tests/plugins/image_gen/test_openai_codex_provider.py b/tests/plugins/image_gen/test_openai_codex_provider.py
index e0d1f2a6e6a..2ae89435b5d 100644
--- a/tests/plugins/image_gen/test_openai_codex_provider.py
+++ b/tests/plugins/image_gen/test_openai_codex_provider.py
@@ -309,60 +309,73 @@ class TestGenerate:
assert result["error_type"] == "api_error"
assert "cloudflare 403" in result["error"]
- def test_unsupported_image_tool_returns_capability_error(self, provider, monkeypatch):
- monkeypatch.setattr(codex_plugin, "_read_codex_access_token", lambda: "codex-token")
-
- def _unsupported(*args, **kwargs):
- raise codex_plugin.CodexImageGenerationUnsupportedError(
- "Tool choice 'image_generation' not found in 'tools' parameter."
- )
-
- monkeypatch.setattr(codex_plugin, "_collect_image_b64", _unsupported)
+ def test_tool_choice_400_surfaces_verbatim_not_as_capability_error(
+ self, provider, monkeypatch
+ ):
+ """The tool_choice 400 must NOT be reported as an account limitation.
+
+ Regression for #19505 / #49008 / #31335: a previous version classified
+ this exact request-shape rejection as "Image generation is not enabled
+ for the current Codex account", telling every affected user to abandon
+ Codex over a bug in our own payload. The wire error must reach the user
+ unedited so it stays diagnosable.
+
+ Drives the REAL httpx boundary (not a mocked ``_collect_image_b64``) so
+ the classification path is actually exercised — mocking the collector
+ would skip the code under test entirely.
+ """
+ import httpx
- result = provider.generate("a cat")
+ monkeypatch.setattr(codex_plugin, "_read_codex_access_token", lambda: "codex-token")
- assert result["success"] is False
- assert result["error_type"] == "capability_unsupported"
- assert "current Codex account" in result["error"]
- assert "OpenAI API key, FAL, or xAI" in result["error"]
-
-
-class TestCapabilityErrorDetection:
- @pytest.mark.parametrize(
- "body",
- [
- "Tool choice 'image_generation' not found in 'tools' parameter.",
- '{"error":{"message":"Tool choice \'image_generation\' not found in \'tools\' parameter."}}',
- ],
- )
- def test_detects_exact_codex_image_tool_rejection(self, body):
- assert codex_plugin._is_image_generation_unsupported_error(400, body) is True
-
- @pytest.mark.parametrize(
- ("status_code", "body"),
- [
- (401, "Tool choice 'image_generation' not found in 'tools' parameter."),
- (400, "Tool choice 'web_search' not found in 'tools' parameter."),
- (400, "The image_generation request was rejected by moderation."),
- (500, "Tool choice 'image_generation' not found in 'tools' parameter."),
- ],
- )
- def test_does_not_misclassify_other_failures(self, status_code, body):
- assert codex_plugin._is_image_generation_unsupported_error(status_code, body) is False
-
- def test_does_not_match_error_message_with_extra_text(self):
body = json.dumps({
"error": {
- "message": (
- "Tool choice 'image_generation' not found in 'tools' parameter "
- "because the request is malformed."
- )
+ "message": "Tool choice 'image_generation' not found in 'tools' parameter.",
+ "type": "invalid_request_error",
+ "param": "tool_choice",
}
})
- assert codex_plugin._is_image_generation_unsupported_error(400, body) is False
+ def _handler(request):
+ return httpx.Response(400, text=body, request=request)
+
+ real_client = httpx.Client
+ monkeypatch.setattr(
+ httpx,
+ "Client",
+ lambda *args, **kwargs: real_client(
+ transport=httpx.MockTransport(_handler),
+ headers=kwargs.get("headers"),
+ timeout=kwargs.get("timeout"),
+ ),
+ )
+
+ result = provider.generate("a cat")
- def test_collect_classifies_exact_http_error_after_large_metadata(self, monkeypatch):
+ assert result["success"] is False
+ assert result["error_type"] == "api_error"
+ assert "HTTP 400" in result["error"]
+ assert "tools' parameter" in result["error"]
+ # The account-entitlement misdiagnosis must not come back.
+ assert "not enabled for the current Codex account" not in result["error"]
+ assert result["error_type"] != "capability_unsupported"
+
+
+class TestRequestShape:
+ def test_payload_omits_tool_choice(self):
+ """Codex rejects every tool_choice shape for hosted image_generation."""
+ payload = codex_plugin._build_responses_payload(
+ prompt="a red circle",
+ size="1024x1024",
+ quality="low",
+ )
+ assert "tool_choice" not in payload
+ # The hosted tool itself is still requested, and instructions do the steering.
+ assert payload["tools"][0]["type"] == "image_generation"
+ assert payload["instructions"]
+
+ def test_http_error_body_is_truncated_but_preserved(self, monkeypatch):
+ """A large error body is capped at 500 chars and still surfaced."""
import httpx
body = json.dumps({
@@ -386,7 +399,7 @@ class TestCapabilityErrorDetection:
),
)
- with pytest.raises(codex_plugin.CodexImageGenerationUnsupportedError):
+ with pytest.raises(RuntimeError, match="HTTP 400") as excinfo:
codex_plugin._collect_image_b64(
"codex-token",
prompt="a cat",
@@ -394,6 +407,11 @@ class TestCapabilityErrorDetection:
quality="low",
)
+ message = str(excinfo.value)
+ # Body is capped, but the actionable wire message still reaches the user.
+ assert "tools' parameter" in message
+ assert len(message) < len(body)
+
# ── Plugin entry point ──────────────────────────────────────────────────────
diff --git a/website/docs/user-guide/features/image-generation.md b/website/docs/user-guide/features/image-generation.md
index 7e890382475..1eead3f0505 100644
--- a/website/docs/user-guide/features/image-generation.md
+++ b/website/docs/user-guide/features/image-generation.md
@@ -122,6 +122,19 @@ FAL models with an editing endpoint: `flux-2/klein/9b`, `flux-2-pro`,
`krea/*`) reject image inputs with a clear error pointing you at an
edit-capable model.
+:::note OpenAI (Codex auth) is best-effort
+
+The Codex surface (`chatgpt.com/backend-api/codex`) hosts `image_generation`
+as a tool the chat model may call, and Hermes cannot force the call — the
+backend rejects every `tool_choice` shape for hosted tools, so the request
+relies on instructions to steer the model. When the host model declines to
+invoke the tool, the call fails with `empty_response`. Whether the hosted
+image tool is reachable at all has also been reported to vary between
+accounts. If you need image generation to work deterministically, configure
+the **OpenAI** (API key), **FAL**, or **xAI** backend instead.
+
+:::
+
The active model's editing capability is surfaced in the tool description at
runtime, so the agent knows whether `image_url` will be honored before it
calls the tool.