Skip to content

The agent that grows with you

fix(image-gen): record token usage as soon as the billed HTTP 200 lands

teknium1255b4fd9da31
diff --git a/plugins/image_gen/openai/__init__.py b/plugins/image_gen/openai/__init__.py
index 260412c758b..be013eebbf1 100644
--- a/plugins/image_gen/openai/__init__.py
+++ b/plugins/image_gen/openai/__init__.py
@@ -143,6 +143,9 @@ class OpenAIImageGenProvider(StaticImageGenProvider):
logger.debug("OpenAI image %s failed", verb, exc_info=True)
return fail(f"OpenAI image {'editing' if is_edit else 'generation'} failed: {exc}", "api_error")
+ # gpt-image bills per text/image token; the tier id is a Hermes label, the API model prices.
+ # Recorded before extraction/save: the tokens are billed whether or not an image came back.
+ record_token_usage(getattr(response, "usage", None), model=meta["api_model"], provider="openai")
data = getattr(response, "data", None) or []
if not data:
return fail("OpenAI returned no image data", "empty_response")
@@ -153,8 +156,6 @@ class OpenAIImageGenProvider(StaticImageGenProvider):
model=tier_id, prompt=prompt, aspect=aspect, log=logger)
if err:
return err
- # gpt-image bills per text/image token; the tier id is a Hermes label, the API model prices.
- record_token_usage(getattr(response, "usage", None), model=meta["api_model"], provider="openai")
extra: Dict[str, Any] = {"size": size, "quality": meta["quality"]}
if getattr(first, "revised_prompt", None):
extra["revised_prompt"] = first.revised_prompt
diff --git a/plugins/image_gen/openrouter/__init__.py b/plugins/image_gen/openrouter/__init__.py
index b7b4eb9a622..7b26a7c9997 100644
--- a/plugins/image_gen/openrouter/__init__.py
+++ b/plugins/image_gen/openrouter/__init__.py
@@ -680,6 +680,8 @@ class OpenRouterCompatImageProvider(ImageGenProvider):
"model_access", retryable=True)
return _fail(failure.error, "api_error", retryable=status in _IMAGE_API_FALLBACK_STATUSES)
+ # The provider billed these tokens on HTTP 200 whether or not an image came back / saved.
+ record_token_usage(_dict_at(body, "usage"), model=model_id, provider=self._name, base_url=base_url)
entries = [e for e in _list_at(body, "data") if isinstance(e, dict)]
if not entries:
return _fail(
@@ -692,7 +694,6 @@ class OpenRouterCompatImageProvider(ImageGenProvider):
return _fail(f"Could not save generated image: {exc}", "io_error")
if not saved:
return _fail(f"{self._display} response carried neither b64_json nor url.", "empty_response")
- record_token_usage(_dict_at(body, "usage"), model=model_id, provider=self._name, base_url=base_url)
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",
@@ -725,6 +726,8 @@ class OpenRouterCompatImageProvider(ImageGenProvider):
return fail(hint, "model_access"), "unavailable"
return fail(failure.error, "api_error"), None
+ # The provider billed these tokens on HTTP 200 whether or not an image came back / saved.
+ record_token_usage(_dict_at(result, "usage"), model=model_id, provider=self._name, base_url=base_url)
images = _extract_images(result)
if not images:
# Text but no image usually means the model didn't honor image output.
@@ -741,7 +744,6 @@ class OpenRouterCompatImageProvider(ImageGenProvider):
saved_path = save_url_image(first, prefix=f"{self._name}_gen")
except Exception as exc: # noqa: BLE001
return fail(f"Could not save generated image: {exc}", "io_error"), None
- record_token_usage(_dict_at(result, "usage"), model=model_id, provider=self._name, base_url=base_url)
return success_response(
image=str(saved_path), model=model_id, prompt=prompt, aspect_ratio=aspect, provider=self._name,
), None
diff --git a/tests/plugins/image_gen/test_openai_provider.py b/tests/plugins/image_gen/test_openai_provider.py
index 9a315cbb079..2797ebee1e0 100644
--- a/tests/plugins/image_gen/test_openai_provider.py
+++ b/tests/plugins/image_gen/test_openai_provider.py
@@ -172,9 +172,11 @@ class TestGenerate:
# gpt-image-2 rejects response_format — we must NOT send it.
assert "response_format" not in call_kwargs
- def test_token_usage_reaches_session_accounting(self, provider):
+ @pytest.mark.parametrize("has_image", [True, False])
+ def test_token_usage_reaches_session_accounting(self, provider, has_image):
"""gpt-image bills per token: the Images API ``usage`` block lands as one
- ``image_generation`` row keyed on the API model, not the Hermes tier label."""
+ ``image_generation`` row keyed on the API model, not the Hermes tier label — also
+ when the billed HTTP 200 carries no image data."""
from agent import aux_accounting
recorded = []
@@ -184,6 +186,8 @@ class TestGenerate:
recorded.append((args, kwargs))
response = _fake_response(b64=_b64_png())
+ if not has_image:
+ response.data = []
response.usage = SimpleNamespace(input_tokens=23, output_tokens=1056, total_tokens=1079)
fake_client = MagicMock()
fake_client.images.generate.return_value = response
@@ -194,7 +198,9 @@ class TestGenerate:
finally:
aux_accounting.reset_accounting_context(token)
- assert result["success"] is True
+ assert result["success"] is has_image
+ if not has_image:
+ assert result["error_type"] == "empty_response"
((session_id, task), kwargs), = recorded
assert (session_id, task) == ("sess-1", "image_generation")
assert (kwargs["model"], kwargs["billing_provider"]) == ("gpt-image-2", "openai")
diff --git a/tests/plugins/image_gen/test_openrouter_compat_provider.py b/tests/plugins/image_gen/test_openrouter_compat_provider.py
index ec6a1aa5a06..09ad4ffb359 100644
--- a/tests/plugins/image_gen/test_openrouter_compat_provider.py
+++ b/tests/plugins/image_gen/test_openrouter_compat_provider.py
@@ -705,14 +705,17 @@ class TestImageApiSurface:
_USAGE = {"prompt_tokens": 1000, "completion_tokens": 128, "total_tokens": 1128}
- @pytest.mark.parametrize("surface, model, usage", [
- ("chat", "openai/gpt-5.4-image-2", _USAGE), # default chain: token-billed via /chat/completions
- ("images", "krea/krea-2-medium", _USAGE), # curated Image API model
- ("images", "krea/krea-2-medium", None), # flat-fee body without usage: no write
+ @pytest.mark.parametrize("surface, model, usage, images", [
+ ("chat", "openai/gpt-5.4-image-2", _USAGE, True), # default chain: token-billed via /chat/completions
+ ("images", "krea/krea-2-medium", _USAGE, True), # curated Image API model
+ ("images", "krea/krea-2-medium", None, True), # flat-fee body without usage: no write
+ ("chat", "openai/gpt-5.4-image-2", _USAGE, False), # billed HTTP 200 with text but no image
+ ("images", "krea/krea-2-medium", _USAGE, False), # billed HTTP 200 with empty ``data``
])
- def test_token_usage_reaches_session_accounting(self, surface, model, usage):
+ def test_token_usage_reaches_session_accounting(self, surface, model, usage, images):
"""A response carrying token usage records one ``image_generation`` row on the ambient
- session; a body without usage records nothing."""
+ session — also when it carries no image (the provider billed the tokens anyway); a body
+ without usage records nothing."""
from agent import aux_accounting
recorded = []
@@ -722,10 +725,10 @@ class TestImageApiSurface:
recorded.append((args, kwargs))
if surface == "chat":
- response = _mock_chat_response([_PNG_DATA_URI])
+ response = _mock_chat_response([_PNG_DATA_URI] if images else [])
response.json.return_value["usage"] = dict(usage)
else:
- response = _mock_image_api_response(usage=usage)
+ response = _mock_image_api_response([] if not images else None, usage=usage)
token = aux_accounting.set_accounting_context(_DB(), "sess-1")
try:
with patch(_RUNTIME, return_value=_runtime_ok()), \
@@ -735,7 +738,9 @@ class TestImageApiSurface:
finally:
aux_accounting.reset_accounting_context(token)
- assert result["success"] is True
+ assert result["success"] is images
+ if not images:
+ assert result["error_type"] == "empty_response"
if usage is None:
assert recorded == []
return