The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): price Responses function_call_output images flat, not as base64 text
Konstantin Khlopkov162c05831a71
diff --git a/agent/model_metadata.py b/agent/model_metadata.pyindex d4374d787e4..52360ca0cec 100644--- a/agent/model_metadata.py+++ b/agent/model_metadata.py@@ -2331,16 +2331,22 @@ def _count_parts(parts: Any, types: set) -> int:return sum(1 for part in parts if isinstance(part, dict) and part.get("type") in types) if isinstance(parts, list) else 0+_IMAGE_PART_TYPES = frozenset({"image", "image_url", "input_image"})++def _count_image_tokens(msg: Dict[str, Any], cost_per_image: int) -> int:"""Count image-like content parts in a message; return their token cost."""if not isinstance(msg, dict):return 0content = msg.get("content")- count = _count_parts(content, {"image", "image_url", "input_image"})+ count = _count_parts(content, _IMAGE_PART_TYPES)count += _count_parts(msg.get("_anthropic_content_blocks"), {"image"})# Multimodal tool results that haven't been converted yet.if isinstance(content, dict) and content.get("_multimodal"):count += _count_parts(content.get("content"), {"image", "image_url"})+ # Responses ``function_call_output`` items carry converted tool-result+ # parts under ``output`` (the converter moves chat ``content`` there).+ count += _count_parts(msg.get("output"), _IMAGE_PART_TYPES)return count * cost_per_image@@ -2384,11 +2390,22 @@ def _wire_message_shadow(msg: Dict[str, Any]) -> Dict[str, Any]:elif k == "content" and isinstance(v, list):shadow[k] = [{"type": part.get("type"), "image": "[stripped]"}- if isinstance(part, dict) and part.get("type") in {"image", "image_url", "input_image"} else part+ if isinstance(part, dict) and part.get("type") in _IMAGE_PART_TYPES+ else partfor part in v]elif k == "content" and isinstance(v, dict) and v.get("_multimodal"):shadow[k] = v.get("text_summary", "")+ elif k == "output" and isinstance(v, list):+ # Responses ``function_call_output`` output parts: strip the image+ # payload like the ``content`` branch above so encoded bytes are+ # priced by the flat per-image model, never as text.+ shadow[k] = [+ {"type": part.get("type"), "image": "[stripped]"}+ if isinstance(part, dict) and part.get("type") in _IMAGE_PART_TYPES+ else part+ for part in v+ ]elif k == "codex_reasoning_items":shadow[k] = strip_opaque_replay_items(v)elif k == "encrypted_content": # a Responses reasoning/compaction item passed as a rowdiff --git a/tests/agent/test_model_metadata.py b/tests/agent/test_model_metadata.pyindex 2076c57759f..1f31a0e4279 100644--- a/tests/agent/test_model_metadata.py+++ b/tests/agent/test_model_metadata.py@@ -163,6 +163,69 @@ class TestEstimateMessagesTokensRough:assert estimate_messages_tokens_rough([msg]) < 5_000+class TestResponsesItemImageAccounting:+ """Responses ``function_call_output`` items carry tool-result images under+ ``output`` (the converter moves chat ``content`` there); the estimator must+ price them with the flat per-image model, never as base64 text (#108320)."""++ def test_function_call_output_image_priced_flat_not_by_base64_length(self):+ import base64+ import os++ small = "data:image/png;base64," + base64.b64encode(os.urandom(8_000)).decode()+ large = (+ "data:image/png;base64," + base64.b64encode(os.urandom(300_000)).decode()+ )++ def estimate(payload: str) -> int:+ item = {+ "type": "function_call_output",+ "call_id": "call_1",+ "output": [{"type": "input_image", "image_url": payload}],+ }+ return estimate_messages_tokens_rough([item])++ small_est, large_est = estimate(small), estimate(large)+ # Flat per-image model: both register as the learned/default image cost+ # plus a small envelope, independent of encoded length.+ assert 1500 <= small_est < 3_000+ assert 1500 <= large_est < 3_000+ assert abs(large_est - small_est) < 200++ def test_function_call_output_image_matches_chat_estimate(self):+ """The carrier key alone (``content`` vs ``output``) must not change the+ accounting for the same image."""+ import base64+ import os++ payload = (+ "data:image/png;base64," + base64.b64encode(os.urandom(100_000)).decode()+ )+ chat = {+ "role": "user",+ "content": [{"type": "image_url", "image_url": {"url": payload}}],+ }+ responses_item = {+ "type": "function_call_output",+ "call_id": "call_1",+ "output": [{"type": "input_image", "image_url": payload}],+ }++ chat_est = estimate_messages_tokens_rough([chat])+ responses_est = estimate_messages_tokens_rough([responses_item])++ assert abs(chat_est - responses_est) < 200++ def test_function_call_output_text_output_still_counted(self):+ """Plain-string ``output`` (the common tool-result shape) is unaffected."""+ item = {+ "type": "function_call_output",+ "call_id": "call_1",+ "output": "plain tool result " * 100,+ }+ est = estimate_messages_tokens_rough([item])+ assert est >= (len(item["output"]) // 4) * 0.9+class TestEstimateRequestTokensRough:def test_caches_tools_estimate(self):