Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(tokenizers): estimate replayed thinking from text and signature size (#3482)
gglucass9ed95c380643
diff --git a/headroom/tokenizers/base.py b/headroom/tokenizers/base.pyindex cc9f12515..8c0e16743 100644--- a/headroom/tokenizers/base.py+++ b/headroom/tokenizers/base.py@@ -328,6 +328,23 @@ class BaseTokenizer(ABC):total += frames * 1000else:total += 3200+ elif part_type == "thinking":+ # Anthropic extended thinking replayed by the client. The+ # ``signature`` is the encrypted full reasoning: on the+ # keep-all-turns models (Opus 4.5+, Sonnet 4.6+, the 5.x+ # line) the server decrypts it into the prompt and bills+ # it as input, and under ``display: "omitted"`` (the 5.x+ # default) the ``thinking`` text is empty, so text alone+ # is not the input. Nor is the base64: the JSON catch-all+ # below priced it as prose at ~3 chars/token, and on a+ # 369-message Claude Code session 99 signatures counted+ # 256K of 414K tokens against ~313K provider-reported.+ # Price the text plus the decoded signature bytes at+ # ~4 bytes/token (len * 3/4 / 4), which lands that session+ # near the provider figure and never prices an omitted+ # block at zero.+ total += self.count_text(part.get("thinking", "") or "")+ total += len(part.get("signature") or "") * 3 // 16else:# Unknown type - estimate from JSONtotal += self._count_serialized(part)diff --git a/tests/test_tokenizers.py b/tests/test_tokenizers.pyindex 524fb38a0..dd8791c2c 100644--- a/tests/test_tokenizers.py+++ b/tests/test_tokenizers.py@@ -727,3 +727,47 @@ class TestLargeToolBlobEstimation:cur = cur["n"]cur["leaf"] = "x" * 60_000assert EstimatingTokenCounter()._count_serialized(deep) >= 0+++class TestThinkingBlockCounting:+ """Thinking blocks price their text plus the decoded signature bytes."""++ def test_signature_prices_between_zero_and_the_json_catch_all(self):+ counter = EstimatingTokenCounter()+ text = "consider the failing test " * 20+ block = {"type": "thinking", "thinking": text, "signature": "A" * 4000}+ signed = {"role": "assistant", "content": [block]}+ unsigned = {"role": "assistant", "content": [{"type": "thinking", "thinking": text}]}+ # The signature is encrypted reasoning the server replays as billed+ # input, so it adds to the text at decoded bytes / 4 (4000 * 3/4 / 4)...+ delta = counter.count_messages([signed]) - counter.count_messages([unsigned])+ assert delta == 750+ # ...which is well under the JSON catch-all's base64-as-prose price.+ assert delta < counter._count_serialized(block)++ def test_omitted_display_block_is_not_free(self):+ # display: "omitted" (the 5.x default) returns an empty thinking field+ # and carries the whole reasoning in the signature.+ counter = EstimatingTokenCounter()+ omitted = {+ "role": "assistant",+ "content": [{"type": "thinking", "thinking": "", "signature": "A" * 4000}],+ }+ empty = {"role": "assistant", "content": [{"type": "thinking", "thinking": ""}]}+ assert counter.count_messages([omitted]) > counter.count_messages([empty])++ def test_provider_walker_shares_the_thinking_rule(self):+ from headroom.tokenizers.base import count_content_blocks++ counter = EstimatingTokenCounter()+ text = "consider the failing test " * 20+ signed = [{"type": "thinking", "thinking": text, "signature": "A" * 4000}]+ unsigned = [{"type": "thinking", "thinking": text}]+ assert count_content_blocks(signed, counter.count_text) == counter._count_content_parts(+ signed+ )+ assert (+ count_content_blocks(signed, counter.count_text)+ - count_content_blocks(unsigned, counter.count_text)+ == 750+ )