Skip to content

Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)

Python

Price tool-result images like top-level images in token estimates (#1895)

rodricksz4h5057b5dfe1bbf
diff --git a/pyproject.toml b/pyproject.toml
index 6f550c25..beb914df 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "free-claude-code"
-version = "6.2.64"
+version = "6.2.65"
description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"
readme = "README.md"
license = "AGPL-3.0-only"
diff --git a/src/free_claude_code/core/anthropic/tokens.py b/src/free_claude_code/core/anthropic/tokens.py
index 72ec3443..cdce8f36 100644
--- a/src/free_claude_code/core/anthropic/tokens.py
+++ b/src/free_claude_code/core/anthropic/tokens.py
@@ -1,15 +1,30 @@
"""Token estimation for Anthropic-compatible requests."""
import json
+from typing import Any
from loguru import logger
from free_claude_code.core.token_estimation import estimate_text_tokens
-from .content import get_block_attr
+from .content import get_block_attr, get_block_type
from .models import Message, SystemContent, Tool
+def _image_tokens(block: Any) -> int:
+ """Estimate one image block from its base64 size, or a flat cost without data.
+
+ Tool-result content is not validated, so ``data`` can be any JSON value there;
+ only a string has a meaningful size, anything else gets the flat cost.
+ """
+ source = get_block_attr(block, "source")
+ if isinstance(source, dict):
+ data = source.get("data") or source.get("base64") or ""
+ if isinstance(data, str) and data:
+ return max(85, len(data) // 3000)
+ return 765
+
+
def get_token_count(
messages: list[Message],
system: str | list[SystemContent] | None = None,
@@ -50,20 +65,21 @@ def get_token_count(
total_tokens += estimate_text_tokens(str(block_id))
total_tokens += 15
elif b_type == "image":
- source = get_block_attr(block, "source")
- if isinstance(source, dict):
- data = source.get("data") or source.get("base64") or ""
- if data:
- total_tokens += max(85, len(data) // 3000)
- else:
- total_tokens += 765
- else:
- total_tokens += 765
+ total_tokens += _image_tokens(block)
elif b_type == "tool_result":
content = get_block_attr(block, "content", "")
tool_use_id = get_block_attr(block, "tool_use_id", "")
if isinstance(content, str):
total_tokens += estimate_text_tokens(content)
+ elif isinstance(content, list):
+ # Images returned by a tool (Read on an image, MCP screenshots)
+ # are priced like top-level images; serializing them would
+ # count their base64 payload as text.
+ images = [p for p in content if get_block_type(p) == "image"]
+ others = [p for p in content if get_block_type(p) != "image"]
+ total_tokens += sum(_image_tokens(image) for image in images)
+ if others or not images:
+ total_tokens += estimate_text_tokens(json.dumps(others))
else:
total_tokens += estimate_text_tokens(json.dumps(content))
total_tokens += estimate_text_tokens(str(tool_use_id))
diff --git a/tests/api/test_request_utils.py b/tests/api/test_request_utils.py
index 9312238e..8c306565 100644
--- a/tests/api/test_request_utils.py
+++ b/tests/api/test_request_utils.py
@@ -1,5 +1,6 @@
"""Tests for API request detection and token counting helpers."""
+import json
from unittest.mock import MagicMock, patch
import pytest
@@ -549,6 +550,78 @@ class TestGetTokenCount:
count = get_token_count([msg])
assert count >= 85
+ def test_image_in_tool_result_costs_the_same_as_a_top_level_image(self):
+ """A tool-returned image (Read on a PNG, an MCP screenshot) is priced as an image.
+
+ Serializing it with the rest of the tool result counted its base64 payload as
+ text: a 300 KB screenshot came out near 215k tokens instead of about 100.
+ """
+ image = {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": "image/png",
+ "data": "A" * 300_000,
+ },
+ }
+ text = {"type": "text", "text": "Screenshot captured"}
+
+ def user_message(*blocks):
+ msg = MagicMock()
+ msg.content = list(blocks)
+ return msg
+
+ def tool_result(*parts):
+ return user_message(
+ {"type": "tool_result", "tool_use_id": "t1", "content": list(parts)}
+ )
+
+ def image_cost(wrap):
+ return get_token_count([wrap(text, image)]) - get_token_count([wrap(text)])
+
+ assert image_cost(tool_result) == image_cost(user_message)
+ assert image_cost(tool_result) < 1_000
+
+ @pytest.mark.parametrize("data", [12345, ["a"], {"x": 1}])
+ def test_tool_result_image_with_non_string_data_gets_the_flat_cost(self, data):
+ """Tool-result content is not validated, so image data can be any JSON value.
+
+ A number used to reach ``len()`` and turn count_tokens into an HTTP 500.
+ """
+ image = {"type": "image", "source": {"type": "base64", "data": data}}
+ msg = MagicMock()
+ msg.content = [{"type": "tool_result", "tool_use_id": "t1", "content": [image]}]
+ no_data = MagicMock()
+ no_data.content = [
+ {
+ "type": "tool_result",
+ "tool_use_id": "t1",
+ "content": [{"type": "image", "source": {"type": "base64"}}],
+ }
+ ]
+
+ assert get_token_count([msg]) == get_token_count([no_data])
+
+ @pytest.mark.parametrize(
+ "parts",
+ [
+ [{"type": "text", "text": "line one"}, {"type": "text", "text": "two"}],
+ [],
+ ],
+ )
+ def test_image_free_tool_result_list_is_counted_as_before(self, parts):
+ """Only images leave the serialized payload; image-free results are unchanged."""
+ msg = MagicMock()
+ msg.content = [{"type": "tool_result", "tool_use_id": "t1", "content": parts}]
+
+ with patch(
+ "free_claude_code.core.anthropic.tokens.estimate_text_tokens",
+ side_effect=len,
+ ):
+ count = get_token_count([msg])
+
+ assert count == len(json.dumps(parts)) + len("t1") + 8 + 4
+
def test_known_payload_structural_overhead(self):
"""Protocol overhead remains separate from plain-text estimation."""
system_text = "You are a helpful assistant."
diff --git a/uv.lock b/uv.lock
index 0853fc12..9183db8a 100644
--- a/uv.lock
+++ b/uv.lock
@@ -599,7 +599,7 @@ wheels = [
[[package]]
name = "free-claude-code"
-version = "6.2.64"
+version = "6.2.65"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },