The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(image-gen): record token-billed OpenRouter calls to session usage
Yagna Vudathu98ad0d8148f3
diff --git a/plugins/image_gen/openrouter/__init__.py b/plugins/image_gen/openrouter/__init__.pyindex 0d1e6a237ce..3a607d1a38d 100644--- a/plugins/image_gen/openrouter/__init__.py+++ b/plugins/image_gen/openrouter/__init__.py@@ -692,6 +692,7 @@ 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_image_api_usage(body, model_id, provider=self._name)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",@@ -802,6 +803,30 @@ class OpenRouterCompatImageProvider(ImageGenProvider):model=model_chain[-1] if model_chain else "", prompt=prompt, aspect_ratio=aspect)+def _record_image_api_usage(body: Any, model_id: str, *, provider: str) -> None:+ """Record a token-billed Image API call against the ambient session (#114324).++ Best-effort: accounting must never break image generation. No-ops outside+ an agent turn or when the response carries no token usage.+ """+ try:+ usage = _dict_at(body, "usage")+ if not isinstance(usage.get("total_tokens"), int):+ return+ from agent.aux_accounting import record_aux_usage+ from types import SimpleNamespace++ record_aux_usage(+ SimpleNamespace(model=model_id, usage=SimpleNamespace(+ prompt_tokens=usage.get("prompt_tokens", 0),+ completion_tokens=usage.get("completion_tokens", 0),+ total_tokens=usage.get("total_tokens", 0),+ )),+ "image_gen", provider=provider)+ except Exception: # noqa: BLE001+ logger.debug("%s: image usage recording failed (non-fatal)", provider, exc_info=True)++def _build_providers() -> List[OpenRouterCompatImageProvider]:return [OpenRouterCompatImageProvider(diff --git a/tests/plugins/image_gen/test_openrouter_compat_provider.py b/tests/plugins/image_gen/test_openrouter_compat_provider.pyindex b3647376b9e..5e36083325c 100644--- a/tests/plugins/image_gen/test_openrouter_compat_provider.py+++ b/tests/plugins/image_gen/test_openrouter_compat_provider.py@@ -703,6 +703,59 @@ class TestImageApiSurface:assert result["exact_aspect_ratio"] == "9:16"assert result["image"] == "/tmp/i.png"+ def test_token_billed_call_records_session_usage(self):+ """#114324: an OpenRouter token-billed call must reach session_model_usage."""+ from agent import aux_accounting++ recorded = []++ class _DB:+ def record_auxiliary_usage(self, *args, **kwargs):+ recorded.append(kwargs)++ token = aux_accounting.set_accounting_context(_DB(), "sess-1")+ try:+ with patch(_RUNTIME, return_value=_runtime_ok()), \+ patch("requests.post", return_value=_mock_image_api_response(+ usage={"total_tokens": 1128, "prompt_tokens": 1000,+ "completion_tokens": 128})), \+ patch("plugins.image_gen.openrouter.save_b64_image", return_value=Path("/tmp/i.png")):+ result = _openrouter_image_api().generate(+ prompt="p", aspect_ratio="portrait", model="krea/krea-2-medium"+ )+ finally:+ aux_accounting.reset_accounting_context(token)++ assert result["success"] is True+ assert len(recorded) == 1+ assert recorded[0]["input_tokens"] == 1000+ assert recorded[0]["output_tokens"] == 128+ assert recorded[0]["model"] == "krea/krea-2-medium"++ def test_untokened_call_records_nothing(self):+ """No token usage in the body: no session write (flat-fee image models)."""+ from agent import aux_accounting++ recorded = []++ class _DB:+ def record_auxiliary_usage(self, *args, **kwargs):+ recorded.append(kwargs)++ token = aux_accounting.set_accounting_context(_DB(), "sess-1")+ try:+ with patch(_RUNTIME, return_value=_runtime_ok()), \+ patch("requests.post", return_value=_mock_image_api_response()), \+ patch("plugins.image_gen.openrouter.save_b64_image", return_value=Path("/tmp/i.png")):+ result = _openrouter_image_api().generate(+ prompt="p", aspect_ratio="portrait", model="krea/krea-2-medium"+ )+ finally:+ aux_accounting.reset_accounting_context(token)++ assert result["success"] is True+ assert recorded == []+def test_multiple_images_land_in_additional_images(self):entries = [{"b64_json": "AA==", "media_type": "image/png"},